asp.net-core Register dependencies


Example

Builtin container comes with a set of builtin features :

Lifetime control

public void ConfigureServices(IServiceCollection services)
    {
        // ...
    
        services.AddTransient<ITestService, TestService>();
        // or
        services.AddScoped<ITestService, TestService>();
        // or
        services.AddSingleton<ITestService, TestService>();
        // or
        services.AddSingleton<ITestService>(new TestService());
    }
  • AddTransient: Created everytime it is resolved
  • AddScoped: Created once per request
  • AddSingleton: Lazily created once per application
  • AddSingleton (instance): Provides a previously created instance per application

Enumerable dependencies

It is also possible to register enumerable dependencies :

 services.TryAddEnumerable(ServiceDescriptor.Transient<ITestService, TestServiceImpl1>());
 services.TryAddEnumerable(ServiceDescriptor.Transient<ITestService, TestServiceImpl2>());

You can then consume them as follows :

public class HomeController : Controller
{
    public HomeController(IEnumerable<ITestService> services)
    {
        // do something with services.
    }
}

Generic dependencies

You can also register generic dependencies :

services.Add(ServiceDescriptor.Singleton(typeof(IKeyValueStore<>), typeof(KeyValueStore<>)));

And then consume it as follows :

public class HomeController : Controller
{
    public HomeController(IKeyValueStore<UserSettings> userSettings)
    {
        // do something with services.
    }
}