Adventures on the edge

Learning new development technologies (2015 - 2018)
    "When living on the bleeding edge - you sometimes have to bleed" -BillKrat

Adding Dependency Injection (Autofac) to ASP.NET MVC Core 2

Where the built-in Inversion Of Control (IOC), aka Dependency Injection (DI), container of ASP.NET MVC will meet most needs, sometimes we’ll want to utilize more advanced features of alternate IOC containers.  In the example below we are configuring for the use of Autofac (line 56), using a pattern consistent with existing code – an extension method.


The extension method AddAutofacProvider code follows below:

Note on line 13 above that we have an optional “builderCallback” action.  This provides the Startup ConfigureService method access to the builder instance created above on line 16.   Below on lines 56-60 is an example of how it might be used:

Source code follows:

public static IServiceProvider AddAutofacProvider(
     this IServiceCollection services,
     Action<ContainerBuilder> builderCallback = null)
     // Instantiate the Autofac builder
     var builder = new ContainerBuilder();

    // If there is a callback use it for registrations

    // Populate the Autofac container with services

    // Create a new container with component registrations
     var container = builder.Build();
     var provider = new AutofacServiceProvider(container);

    // When application stops then dispose container
         .ApplicationStopped.Register(() => container.Dispose());

    // Return the provider
     return provider;

Comments are closed