In this article, I won’t explain what is dependency injection (DI). I will try to explain how DI in ASP.NET Core works what can we do with it and how we can use other DI containers (Autofac and Castle Windsor) with ASP.NET Core.ASP.NET Core provides a minimal feature set to use default services cotainer. But you want to use different DI containers, because DI in ASP.NET Core is vey primitive. For example, it dosn’t support property injection or advanced service registering methods.

Let’s go to the examples and try to understand basics of DI in ASP.NET Core.

class Program
{
    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
 
        services.AddTransient<MyService>();
 
        var serviceProvider = services.BuildServiceProvider();
        var myService = serviceProvider.GetService<MyService>();
 
        myService.DoIt();
    }
}
 
public class MyService
{
    public void DoIt()
    {
        Console.WriteLine("Hello MS DI!");
    }
}

IServiceCollection is the collection of the service descriptors. We can register our services in this collection with different lifestyles (Transient, scoped, singleton)

IServiceProvider is the simple built-in container that is included in ASP.NET Core that supports constructor injection by default. We are getting regisered services with using service provider.

Service Lifestyle/Lifetimes

We can configure services with different types of lifestyles like following.

Transient

This lifestyle services are created each time they are requested.

Scoped

Scoped lifestyle services are created once per request.

Singleton

A singleton service is created once at first time it is requested and this instance of service is used by every sub-requests.

Let’s try to understand better with doing some examples. First, I am creating service classes.

public class TransientDateOperation
{
    public TransientDateOperation()
    {
        Console