Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Autofac with Asp.net core 2.2

I have follow guide at: https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html

At last step, it show:

// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);

However, last version of Asp Net core 2.2, the function ConfigureServices(IServiceCollection services) is return void

public void ConfigureServices(IServiceCollection services)

How can I refactor my code follow latest change ?

like image 223
phuongnd Avatar asked Dec 13 '25 01:12

phuongnd


1 Answers

In your solution you used void return type in ConfigureServices method:

public void ConfigureServices(IServiceCollection services)

Actually you can setup and return IServiceProvider:

public class Startup 
{
  public IContainer Container { get; private set; }

  // ...

  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    // create new container builder
    var containerBuilder = new ContainerBuilder();
    // populate .NET Core services
    containerBuilder.Populate(services);
    // register your autofac modules
    containerBuilder.RegisterModule(new ApiModule());

    // build container
    Container = containerBuilder.Build();

    // return service provider
    return new AutofacServiceProvider(Container);
}

See more details in official documentation

like image 135
Michał Jarzyna Avatar answered Dec 15 '25 22:12

Michał Jarzyna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!