ASP.NET Core – Dependency Injection and Middlewares

Services

assume we have logger service like

public interface ILog
{
    void info(string str);
}

class MyConsoleLogger : ILog
{
    public void info(string str)
    {
        Console.WriteLine(str);
    }
}

then we can register it in ioc like


builder.Services.Add(new ServiceDescriptor(typeof(ILog), typeof( MyConsoleLogger)));

in the above example the service it singleton by default

  1. Singleton: IoC container will create and share a single instance of a service throughout the application’s lifetime.
  2. Transient: The IoC container will create a new instance of the specified service type every time you ask for it.
  3. Scoped: IoC container will create an instance of the specified service type once per request and will be shared in a single request.
public void ConfigureServices(IServiceCollection services)
{
    services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));    // singleton
    
    services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient
    
    services.Add(new ServiceDescriptor(typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped));    // Scoped
}

access to service

var services = this.HttpContext.RequestServices;
var log = (ILog)services.GetService(typeof(ILog));
// or in controller api parameter you can access it by 
[FromServices] IReCaptcha reCaptcha