static void

ASP.Net Core Dependency Injection


There is a simple DI built into core (using IServiceProvider, which goes back to .net 1.1 but now is in Microsoft.Extensions.DependencyInjection.Abstractions).
It's functional enough that a full DI container isn't required, but the usual suspects have hooks.

Eg Autofac, add Autofac.Extensions.DependencyInjection and in Program.cs:

.UseServiceProviderFactory(new AutofacServiceProviderFactory()) //etc


Services are configured in Startup.ConfigureServices(IServiceCollection services)

Most middleware services are added using the standard services.AddX convention.

public void ConfigureServices(IServiceCollection services)
    // Add middleware services.
    // Add application services.

    //newly created each time
    //created for request, reused within request
    //create a singleton, created here
    services.AddSingleton<IService>(new Service());
    //create a singleton, created lazily


Consume using constructor injection- chained dependencies are fine.

If absolutely necessary to break DI, you can also access Service-Locator style, from HttpContext.RequestServices


You can use something similar in consoles, but it's overkill when you just want simple configuration, DI and logging. It's best to call the Host.CreateDefaultBuilder, grab the IServiceProvider from it, and GetRequiredService of your class, which is now fully DI configured for you.

This sample uses NLog. If you have disposables in your services, you'll need to cast the service as IDisposable within a using block.

class Program
    static async Task Main(string[] args)
        var logger = LogManager.GetCurrentClassLogger();
            var host = CreateHostBuilder(args).Build();
            //we don't use the host, just grab the DI container which has been built with options
            var serviceProvider = host.Services;
            var runner = serviceProvider.GetRequiredService<Runner>();
        catch (Exception ex)
            // NLog: catch any exception and log it.
            logger.Error(ex, "Top level exception");
            // Flush and stop internal timers/threads
    public static IHostBuilder CreateHostBuilder(string[] args) =>
            .ConfigureServices((hostContext, services) =>
                services.AddLogging(loggingBuilder =>
                    // configure Logging with NLog