如何将Autofac与Asp.net Core 2.2集成

phu*_*gnd 1 c# dependency-injection autofac .net-core asp.net-core

我已遵循以下指南:https : //autofac.readthedocs.io/en/latest/integration/aspnetcore.html

在最后一步,它显示:

// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);
Run Code Online (Sandbox Code Playgroud)

但是,最新版本的Asp Net core 2.2中,函数ConfigureServices(IServiceCollection services)返回void

public void ConfigureServices(IServiceCollection services)
Run Code Online (Sandbox Code Playgroud)

如何根据最新更改重构代码?

Mic*_*yna 6

在您的解决方案中,您void在ConfigureServices方法中使用了返回类型:

public void ConfigureServices(IServiceCollection services)
Run Code Online (Sandbox Code Playgroud)

实际上,您可以设置并返回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);
}
Run Code Online (Sandbox Code Playgroud)

官方文档中查看更多详细信息