Adding AutoFac as Inversion of Control (IoC) mechanism in Asp.Net Core 2.2

Seamless Integration

Adding AutoFac as Inversion of Control (IoC) mechanism in Asp.Net Core 2.2

  1. Include AutoFac and Autofac.Extensions.DependencyInjection packages in your project

Install-Package Autofac.Extensions.DependencyInjection
Install-Package Autofac

2. In the Startup Class, add an Autfac Container Object:

public IContainer Container { get; private set; }

3. Build the Container and Register the Entities within the ConfigureServices method. Populate the .Net Core Services in the AutoFac Container

            //AutoFac:
            var builder = new ContainerBuilder();          
            builder.RegisterType<Items>().As<IEntity>();
            builder.RegisterType<Units>().As<IEntity>();
            builder.RegisterType<Brands>().As<IEntity>();
            builder.RegisterType<Categories>().As<IEntity>();
            builder.RegisterType<SubCategories>().As<IEntity>();
            builder.Populate(services);
            Container = builder.Build();

4. Return AutoFacServiceProvider and change the return type of ConfigureServices to IServiceProvider

//change the return type from void to IServiceProvider:
public IServiceProvider ConfigureServices(IServiceCollection services)

//return AutoFacServiceProvider:
return new AutofacServiceProvider(Container);

5. Services within the .Net ServiceCollection can now be used for IoC anywhere in the code:

private readonly AssetTrackingDBContext _context;
public ItemsController(AssetTrackingDBContext context)
{
    _context = context;
}


No Comments

Add your comment

17 − 9 =