Updated on

Simple Injector is an open-source dependency injection library for .NET. We register our services in its Container once, give each one a lifestyle, and the container checks the whole configuration before the application does any real work.

To download the source code for this article, you can visit our GitHub repository.

Let’s dig in.

What Is Simple Injector?

Simple Injector is a dependency injection container for .NET. We tell its Container which implementation to use for each abstraction, and the container then builds our objects along with everything their constructors need.

The package targets .NET Standard, so the same NuGet package works in a console app, a desktop app and an ASP.NET Core application on .NET 10.

Registrations go through a handful of methods. Register() maps an abstraction to one implementation, Collection.Register() maps it to several, and RegisterInstance() hands the container an object we created ourselves.

Every registration has a lifestyle. Transient is the default, and Scoped and Singleton are one argument away.

Simple Injector also checks its own configuration. Verify() creates every registered type once and throws when a dependency is missing or when a singleton depends on a shorter-lived component. Since version 5, the container runs the same check by itself on the first GetInstance() call, so a wiring mistake shows up the first time we resolve anything.

More about Simple Injector can be found on GitHub and their website.

Before we start setting up Simple Injector please refer to our previous articles: Dependency Injection in ASP.NET Core and SOLID Principles in C# – Dependency Inversion Principle to refresh your memory about dependency injection. 

How Do We Set Up Simple Injector?

Let’s start by creating a console application using .NET CLI:

dotnet new console --name SimpleInjectorExample

Next, let’s move into the new SimpleInjectorExample folder and add the SimpleInjector package to our application:

dotnet add package SimpleInjector

Now we can create services and configure Simple Injector. Let’s create ILogger interface:

public interface ILogger
{
    void Information(string message);
}

The ConsoleLogger class implements ILogger :

public class ConsoleLogger : ILogger
{
    public void Information(string message)
    {
        Console.WriteLine($"[ Information: {DateTime.Now} ] {message}");
    }
}

Our services are ready, so the next step is to wire up the Simple Injector container. For this purpose let’s create ContainerManager class:

using SimpleInjector;

public class ContainerManager
{
    private static readonly Lazy<Container> _container = new(ConfigureServices);
    
    private static Container ConfigureServices()
    {
        var container = new Container();
        container.Register<ILogger, ConsoleLogger>();
        container.Verify();
        return container;
    }

    public static Container Instance => _container.Value;
}

The ConfigureServices() method handles creating and configuring the Simple Injector container. Once the container is configured the next step is to verify it by calling the Verify() method. Calling Verify() ourselves is optional, because since version 5 the container verifies itself on the first GetInstance() call. It’s still good practice: the call reports configuration issues right where we build the container, and a unit test can make the same call. At this point, we can use the ContainerManager class to access instances.

Let’s look at the usage example:

static void RunLogger()
{
    var logger = ContainerManager.Instance.GetInstance<ILogger>();
    logger.Information("Hello SimpleInjector");
}

Which Type Mappings Are Available in Simple Injector?

In the previous example, we used Register() method to define a one-to-one mapping between the interface ILogger and the implementation class ConsoleLogger. In addition to one-to-one mapping Simple Injector also supports one-to-many object mapping. One-to-many object mapping is a way of defining a set of implementations for a given abstraction.

To better understand let’s look at a code example:

public interface INotification
{
    void Notify(string notification);    
}

The INotification interface is an abstract definition. Next, we will create multiple classes that implement INotification interface.

Let’s start by defining EmailNotification class:

public class EmailNotification : INotification
{
    public void Notify(string notification)
    {
        Console.WriteLine($"[ Email Notification : {DateTime.Now} ] {notification}");
    }
}

Similarly, let’s create another class called SMSNotification:

public class SMSNotification : INotification
{
    public void Notify(string notification)
    {
        Console.WriteLine($"[ SMS Notification : {DateTime.Now} ] {notification}");
    }
}

Both SMSNotification and EmailNotification implement the INotification interface. This means we can configure our container to comprise the one-to-many object mapping:

private static Container ConfigureServices()
{
    ...
    container.Collection.Register<INotification>(typeof(EmailNotification), typeof(SMSNotification));
    container.Verify();
    ...
}

To update our container, we had to add one line wiring up before calling the  Verify method. At this point, everything is set and we can request instances of INotification from the container:

static void RunNotificationServices(string notification)
{
    var notificationServices = ContainerManager.Instance.GetAllInstances<INotification>();
    foreach(var service in notificationServices)
    {
        service.Notify(notification);
    }    
}

Inside the RunNotificationServices method, GetAllInstances returns an IEnumerable<INotification> with all the notification service instances. Then we invoked the Notify method by iterating over each instance.

The collection comes back in the order we passed the types to Collection.Register(), so here the email notification runs before the SMS one.

How Do We Register Types in Simple Injector?

Simple Injector provides different ways of registering a type. In this section we will look at three commonly used ways of registering types:

  • Manually created instance
  • Instance created using delegate
  • Auto-Wiring

Manually Created Instance

The next examples use a few types this article doesn’t print. We copy them from the SimpleInjectorExample project in the source code (the Models folder, SampleData.cs, the IUserRepository, IAddressRepository and IUserService interfaces from Spec, and the UserRepository and AddressRepository classes from Services) and import their namespaces in a new GlobalUsings.cs file:

global using SimpleInjectorExample;
global using SimpleInjectorExample.Models;
global using SimpleInjectorExample.Services;
global using SimpleInjectorExample.Spec;

To configure our container with a manually created instance all we have to do is pass an instance when calling RegisterInstance() method:

private static Container ConfigureServices()
{
     ...
     container.RegisterInstance<IUserRepository>(new UserRepository());
     container.Verify();
     ...
}

In the code example above we have configured our container to return a single instance of UserRepository whenever an instance of IUserRepository is requested. The Simple Injector documentation suggests creating instances by hand only when auto-wiring isn’t possible or when the constructor has no dependencies of its own.

Instance Created Using Delegate

In this section, we will update our IUserRepository configuration to use a delegate instead of a manually created instance:

private static Container ConfigureServices()
{
    ...
    container.Register<IUserRepository>(() => new UserRepository());
    container.Verify();
    ...
}

The Register method accepts delegate as an argument which helps us configure our container using a delegate. It is good practice to use this method of wiring containers when working with third-party application components and frameworks.

Auto-Wiring

Simple Injector comprises Auto-Wiring feature which provides the capability to automatically create a type based on type information (constructor arguments). The prerequisites for Simple Injector to provide auto-wiring are:

  • The type must be a concrete implementation
  • There should only be one public constructor(which can be the default constructor). And, all arguments must be resolvable by the container
  • Constructor arguments should not be optional

Let’s add auto-wiring to the example code:

public class UserService : IUserService
{
    private readonly IAddressRepository _addressRepository;
    private readonly IUserRepository _userRepository;

    public UserService(IAddressRepository addressRepository, IUserRepository userRepository)
    {
        _addressRepository = addressRepository;
        _userRepository = userRepository;
    }

    public UserDetail GetUserDetail(int userId)
    {
        var user = _userRepository.GetUser(userId);
        var address = _addressRepository.GetUserAddress(userId);
        
        return new(user, address);
    }
}

We have created UserService class that has one public constructor that has two parameters. For Simple Injector to infer the two parameters let’s update our DI container:

private static Container ConfigureServices()
{
    ...
    container.Register<IUserRepository>(() => new UserRepository());
    container.Register<IAddressRepository, AddressRepository>();
    container.Register<IUserService, UserService>();
    container.Verify();
    ... 
}

Now, Simple Injector knows how to resolve both IUserRepository and IAddressRepository instances. Moreover, it can create instances  UserService whenever an instance of IUserService is requested.

Which Lifestyles Does Simple Injector Support?

Object lifetime determines the number of instances a configured service will have and the lifetime of those instances. By default, Simple Injector provides three dependency injection lifestyles: Transient, Scoped, and Singleton.

If you’re not familiar with dependency injection lifestyles check out our article Dependency Injection Lifetimes in ASP.NET Core to learn more.

In addition to these three lifestyles Simple Injector provides a way to define a custom lifestyle. Defining a custom lifestyle is outside the scope of this article.

Transient

In Simple Injector the default lifestyle is Transient. For transient types, the container creates a corresponding instance every time we request a service. The container does not keep track of transient instances. The Simple Injector documentation explains why: “Transient instances are not tracked by the container as tracking transient instances is a common source of memory leaks.”

Therefore, they are not disposed of by the container. In the previous code examples, the instance lifetime is not explicitly stated, therefore they are configured as Transient:

//Lifetime explicitly set to Transient 
container.Register<IUserService, UserService>(Lifestyle.Transient);

//by default lifetime is set to Transient
container.Register<IAddressRepository, AddressRepository>();

Scoped

The container creates a single instance for every request within the defined scope. And, tracks the instances. After the completion of the scope, the container disposes of the instances.

To change the lifetime of IAddressRepository we change the Lifestyle value and define the scope of lifestyle:

using SimpleInjector.Lifestyles;

private static Container ConfigureServices()
{
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
    ... 
    container.Register<IAddressRepository, AddressRepository>(Lifestyle.Scoped);
    ...
}

Web Request and WCF Operations implement scoping implicitly. In ASP.NET Core, Simple Injector’s integration package starts and ends a scope around every request for us. However, for this example, we are using a console application. Hence, we must specify the lifestyle of the scope and when we want to request for scope instance we should start and finish the scope.

using SimpleInjector.Lifestyles;

static void PingUser(int userId)
{
    using var scope = AsyncScopedLifestyle.BeginScope(ContainerManager.Instance);
    var service = ContainerManager.Instance.GetInstance<IUserService>();
    var logger = ContainerManager.Instance.GetInstance<ILogger>();
    
    var detail = service.GetUserDetail(userId);
    var userInfo = $"{detail.User.FirstName} {detail.User.LastName}";
    var address = $" {detail.Address.City} - {detail.Address.Zone}";
    
    logger.Information($"PINGING USER Name: {userInfo}, Address: {address}");
    RunNotificationServices($"Hello {detail.User.FirstName} {detail.User.LastName}");
}

The core implementation of IUserService is dependent on IAddressRepository (which has the scoped lifestyle). Since this is a console application we must start the scope manually by invoking BeginScope() method. The scope instance keeps track of the scoped components and prevents the creation of another instance within the scope. At the end of using block the scope and the disposable scoped instances it tracks are automatically disposed of.

Singleton

There will only be one instance of the registered service type. The container tracks the single instance. The instance is disposed of when the container is disposed of.

We can change the lifetime simply by changing the Lifestyle value:

container.Register<ILogger, ConsoleLogger>(Lifestyle.Singleton);

It is possible to mix dependencies between components that have different lifetimes. One rule to keep in mind is that a component can only be dependent on components that have equal or longer lifetimes. For example, a transient service can depend on scoped or singleton services, but a singleton can’t depend on a scoped or transient one. Simple Injector 5 makes one exception by default: a scoped service may depend on a transient one. Calling the Verify method after configuring our container catches the other cases early.

What Does Verify() Catch in Simple Injector?

Verify() builds every registration in the container once and then runs Simple Injector’s diagnostic checks over the result.

Here are two mistakes it catches. The first is a missing registration: a constructor asks for a type the container doesn’t know, and Verify() throws an InvalidOperationException that names the parameter it couldn’t resolve.

The second is a lifestyle mismatch. A component holds on to something that should live for a shorter time than the component itself. A singleton UserService that receives a scoped AddressRepository would keep that one repository for the life of the application. The diagnostics report this as a warning, and Verify() collects every warning into one DiagnosticVerificationException that lists all of them.

Since version 5, the check runs even if we never call Verify(). The container verifies itself on the first GetInstance() call and checks every registration, including ones unrelated to the service we asked for. Calling it ourselves is still the better habit, since it always fails in the same place.

Don’t copy this configuration: we break it on purpose. UserService becomes a singleton while IAddressRepository stays scoped:

using SimpleInjector;
using SimpleInjector.Lifestyles;

var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<IUserRepository, UserRepository>(Lifestyle.Singleton);
container.Register<IAddressRepository, AddressRepository>(Lifestyle.Scoped);
container.Register<IUserService, UserService>(Lifestyle.Singleton);

try
{
    container.Verify();
}
catch (DiagnosticVerificationException ex)
{
    Console.WriteLine(ex.Message);
}

IUserRepository is a singleton here too, so the only mismatch the output reports is the scoped one. When we run it, the container prints:

The configuration is invalid. The following diagnostic warnings were reported:
-[Lifestyle Mismatch] UserService (Singleton) depends on IAddressRepository implemented by AddressRepository (Async Scoped).
See the Error property for detailed information about the warnings. Please see https://simpleinjector.org/diagnostics how to fix problems and how to suppress individual warnings.

The fix is to give UserService a lifestyle no longer than its dependencies. In our sample it stays transient, the default. The sample’s test project keeps this broken configuration in a test, so the check runs with every test run.

When Should We Use Simple Injector Instead of the Built-In Container?

.NET already ships a dependency injection container, Microsoft.Extensions.DependencyInjection, and ASP.NET Core and the generic host use it out of the box. For many applications it’s enough, and then we keep it.

We’d reach for Simple Injector when we want more checking than the built-in container does. The built-in container can check that every service can be created and that scoped services stay out of the root provider, through ValidateOnBuild and ValidateScopes. Simple Injector’s diagnostics also flag a singleton that depends on a transient component, and warn about disposable transient registrations.

Decorators are the other common reason. RegisterDecorator() wraps every implementation of an abstraction in a decorator with one line, which the built-in container leaves to extra packages such as Scrutor.

It also works with no host at all, which is how this article uses it.

The cost is a second container to learn and, in ASP.NET Core, an integration package that connects the two. Autofac is the other container teams usually compare it with.

We explain the decorator pattern separately, and we also have articles on Scrutor, which adds decorator support to the built-in container, and on Autofac.

There’s an article that shows how different IoC containers compare to each other, so you might want to check it out: IoC Container Benchmark – Performance comparison

Conclusion

In this article, we’ve learned what Simple Injector is, the different aspects of configuring a Simple Injector container, the lifestyles it supports, and how Verify() catches wiring mistakes before they reach a running request.

Tested with .NET 10.0.10 and Simple Injector 5.6.0.