Convert Figma logo to code with AI

simpleinjector logoSimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.

1,208
155
1,208
29

Top Related Projects

4,466

An addictive .NET IoC container

1,513

Castle Windsor is a best of breed, mature Inversion of Control container available for .NET

1,659

This repository contains all relevant information about Unity Container suit

2,667

the ninja of .net dependency injectors

Quick Overview

Simple Injector is a popular dependency injection (DI) container for .NET. It's designed to be easy to use, lightweight, and fast, while still providing advanced features for complex scenarios. Simple Injector helps developers implement the Dependency Inversion Principle in their applications, promoting loose coupling and better testability.

Pros

  • Fast performance and low memory footprint
  • Easy to use with a clean, fluent API
  • Supports advanced scenarios like decorators, interception, and context-based injection
  • Extensive documentation and active community support

Cons

  • Steeper learning curve for advanced features compared to some other DI containers
  • Not as widely adopted as some alternatives (e.g., Microsoft.Extensions.DependencyInjection)
  • May require more manual configuration compared to convention-based containers

Code Examples

  1. Basic registration and resolution:
var container = new Container();
container.Register<IUserRepository, SqlUserRepository>();
container.Register<IUserService, UserService>();

var userService = container.GetInstance<IUserService>();
  1. Registering a singleton:
container.RegisterSingleton<ILogger, FileLogger>();
  1. Conditional registration:
container.Register<IMessageSender>(() => 
    Config.UseEmail ? new EmailSender() : new SmsSender());
  1. Decorator registration:
container.Register<ICommandHandler<CreateUserCommand>, CreateUserCommandHandler>();
container.RegisterDecorator(typeof(ICommandHandler<>), typeof(LoggingCommandHandlerDecorator<>));

Getting Started

  1. Install the NuGet package:

    Install-Package SimpleInjector
    
  2. Create and configure the container:

    var container = new Container();
    container.Register<IUserRepository, SqlUserRepository>();
    container.Register<IUserService, UserService>();
    container.Verify();
    
  3. Use the container to resolve dependencies:

    var userService = container.GetInstance<IUserService>();
    

For more advanced usage and integration with specific frameworks, refer to the official documentation at https://simpleinjector.org/documentation.

Competitor Comparisons

4,466

An addictive .NET IoC container

Pros of Autofac

  • More flexible configuration options, allowing for complex scenarios
  • Extensive module system for organizing registrations
  • Better support for generic decorators and interception

Cons of Autofac

  • Steeper learning curve due to its complexity
  • Slightly slower performance in some scenarios
  • Larger memory footprint compared to SimpleInjector

Code Comparison

SimpleInjector:

var container = new Container();
container.Register<IUserRepository, SqlUserRepository>();
container.Register<IUserService, UserService>();

Autofac:

var builder = new ContainerBuilder();
builder.RegisterType<SqlUserRepository>().As<IUserRepository>();
builder.RegisterType<UserService>().As<IUserService>();
var container = builder.Build();

Both SimpleInjector and Autofac are popular dependency injection containers for .NET applications. SimpleInjector focuses on simplicity and performance, making it easier to learn and use for straightforward scenarios. It also boasts excellent performance characteristics.

Autofac, on the other hand, offers more advanced features and flexibility, making it suitable for complex applications with intricate dependency graphs. However, this comes at the cost of a steeper learning curve and slightly lower performance in some cases.

The choice between the two often depends on the specific requirements of the project and the development team's preferences.

1,513

Castle Windsor is a best of breed, mature Inversion of Control container available for .NET

Pros of Windsor

  • More feature-rich with advanced capabilities like interceptors and typed factories
  • Supports multiple lifestyles (scopes) for better control over object lifecycles
  • Extensive documentation and a large, active community

Cons of Windsor

  • Steeper learning curve due to its complexity and numerous features
  • Slightly slower performance compared to SimpleInjector
  • Larger memory footprint and increased assembly size

Code Comparison

Windsor:

container.Register(Component.For<IService>().ImplementedBy<Service>());
container.Register(Component.For<IRepository>().ImplementedBy<Repository>());
var service = container.Resolve<IService>();

SimpleInjector:

container.Register<IService, Service>();
container.Register<IRepository, Repository>();
var service = container.GetInstance<IService>();

Both Windsor and SimpleInjector are popular dependency injection containers for .NET applications. Windsor offers more advanced features and flexibility, making it suitable for complex projects with specific requirements. SimpleInjector, on the other hand, focuses on simplicity and performance, making it a good choice for projects that prioritize speed and ease of use. The code comparison shows that both containers have similar basic usage, but Windsor's syntax is slightly more verbose due to its additional configuration options.

1,659

This repository contains all relevant information about Unity Container suit

Pros of Unity

  • More extensive feature set, including support for interception and lifetime management
  • Better integration with Microsoft technologies and frameworks
  • Larger community and ecosystem, potentially leading to more resources and support

Cons of Unity

  • Steeper learning curve due to its complexity and extensive features
  • Slower performance compared to SimpleInjector, especially in large-scale applications
  • More verbose configuration and setup process

Code Comparison

SimpleInjector:

var container = new Container();
container.Register<IUserRepository, SqlUserRepository>();
container.Register<IUserService, UserService>();

Unity:

var container = new UnityContainer();
container.RegisterType<IUserRepository, SqlUserRepository>();
container.RegisterType<IUserService, UserService>();

Both SimpleInjector and Unity are popular dependency injection containers for .NET applications. SimpleInjector focuses on simplicity, performance, and ease of use, while Unity offers a more comprehensive set of features and better integration with Microsoft technologies. The choice between the two depends on the specific requirements of your project, such as performance needs, complexity, and integration with other frameworks.

2,667

the ninja of .net dependency injectors

Pros of Ninject

  • More flexible and customizable with a wide range of extensions
  • Supports advanced scenarios like contextual binding and multi-injection
  • Has a larger community and ecosystem

Cons of Ninject

  • Slower performance compared to SimpleInjector
  • More complex API, which can lead to a steeper learning curve
  • Larger memory footprint

Code Comparison

Ninject:

var kernel = new StandardKernel();
kernel.Bind<IWeapon>().To<Sword>();
var warrior = kernel.Get<Samurai>();

SimpleInjector:

var container = new Container();
container.Register<IWeapon, Sword>();
var warrior = container.GetInstance<Samurai>();

Both SimpleInjector and Ninject are popular dependency injection containers for .NET applications. SimpleInjector focuses on simplicity and performance, while Ninject offers more flexibility and features. SimpleInjector generally performs better and has a simpler API, making it easier to learn and use. However, Ninject's extensive customization options and larger ecosystem make it suitable for more complex scenarios. The choice between the two depends on the specific requirements of your project and your preference for simplicity versus flexibility.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Simple Injector

NuGet

To get a high level overview of Simple Injector, please visit our website or dive directly into our documentation. And did you know there's a Simple Injector blog?

The goal of Simple Injector is to provide .NET application developers with an easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.

Many of the existing DI libraries have a big complicated legacy API or are new, immature, and lack features often required by large scale development projects. Simple Injector fills this gap by supplying a simple implementation with a carefully selected, but complete set of features that allow you to write highly maintainable applications. Features like decorator registration and container-verification set it apart from the other containers. In the end, you will realize that there only two types of DI Containers—Simple Injector... and the rest.

The following platforms are supported:

  • .NET 4.5 and up.
  • .NET Standard including:
    • Universal Windows Programs.
    • Mono.
    • .NET Core, .NET 5 and up.
    • Xamarin.

Simple Injector is carefully designed to run in partial / medium trust, and it is fast; blazingly fast.

Getting started

The easiest way to get started is by installing the available NuGet packages. Take a look at the Using section in the documentation on learning how to configure and use Simple Injector. Go to the Integration page to find out how to integrate Simple Injector in your favorate application framework. Look at the More Information section to learn more or if you have any questions.

A Quick Example

Dependency Injection

The general idea behind Simple Injector (or any DI library for that matter) is that you design your application around loosely coupled components using the dependency injection pattern while adhering to the Dependency Inversion Principle. Take for instance the following UserController class in the context of an ASP.NET MVC application:

Note: Simple Injector works for many different technologies and not just MVC. Please see the integration for help using Simple Injector with your technology of choice.

public class UserController : Controller
{
    private readonly IUserRepository repository;
    private readonly ILogger logger;

    // Use constructor injection for the dependencies
    public UserController(IUserRepository repository, ILogger logger)
    {
        this.repository = repository;
        this.logger = logger;
    }

    // implement UserController methods here:
    public ActionResult Index()
    {
        this.logger.Log("Index called");
        return View(this.repository.GetAll());
    }
}
    
public class SqlUserRepository : IUserRepository
{
    private readonly ILogger logger;

    // Use constructor injection for the dependencies
    public SqlUserRepository(ILogger logger)
    {
        this.logger = logger;
    }
    
    public User GetById(Guid id)
    {
        this.logger.Log("Getting User " + id);
        // retrieve from db.
    }
}

The UserController class depends on the IUserRepository and ILogger interfaces. By not depending on concrete implementations, you can test UserController in isolation. But ease of testing is only one of a number of things that Dependency Injection gives you. It also enables you, for example, to design highly flexible systems that can be completely composed in one specific location (often the startup path) of the application.

Introducing Simple Injector

Using Simple Injector, the configuration of the application using the UserController and SqlUserRepository classes shown above, might look something like this:

protected void Application_Start(object sender, EventArgs e)
{
    // 1. Create a new Simple Injector container
    var container = new Container();

    // 2. Configure the container (register)
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Transient);
    container.Register<ILogger, MailLogger>(Lifestyle.Singleton);   
    container.Register<UserController>();

    // 3. Optionally verify the container's configuration.
    container.Verify();

    // 4. Register the container as MVC3 IDependencyResolver.
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

Tip: If you start with a MVC application, take a look at the ASP.NET MVC integration guide.

The given configuration registers implementations for the IUserRepository and ILogger interfaces. The code snippet shows a few interesting things. First of all, you can map concrete instances (such as SqlUserRepository) to an interface or base type. In the given example, every time you ask the container for an IUserRepository, it will always create a new SqlUserRepository on your behalf (in DI terminology: an object with a Transient lifestyle).

The seconds registration maps the ILogger interface to a MailLogger implementation. This MailLogger is registered with the Singleton lifestyle—only one instance of MailLogger will ever be created by the Container.

Using this configuration, when a UserController is requested, the following object graph is constructed:

new UserController(
    new SqlUserRepository(
        logger),
    logger);

Note that object graphs can become very deep. What you can see is that not only UserController contains dependencies, so does SqlUserRepository. In this case SqlUserRepository itself contains an ILogger dependency. Simple Injector will not only resolve the dependencies of UserController but will instead build a whole tree structure of any level deep for you.

And this is all it takes to start using Simple Injector. Design your classes around the SOLID principles and the Dependency Injection pattern (which is actually the hard part) and configure them during application initialization. Some frameworks (such as ASP.NET MVC) will do the rest for you, other frameworks (like ASP.NET Web Forms) will need a little bit more work. See the integration guide for examples of many common application frameworks.

Please go to the using section in the documentation to see more examples.

More information

For more information about Simple Injector please visit the following links:

Happy injecting!