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.

AutoFac01

The extension method AddAutofacProvider code follows below:
AutoFac02

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:
AutoFac03

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
     builderCallback?.Invoke(builder);

    // Populate the Autofac container with services
     builder.Populate(services);

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

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

    // Return the provider
     return provider;
}






Comments are closed