如何将Autofac与Asp.net核心2.2集成

问题描述 投票:0回答:1

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

最后一步,它显示:

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

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

public void ConfigureServices(IServiceCollection services)

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

c# asp.net-core dependency-injection .net-core autofac
1个回答
3
投票

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

public void ConfigureServices(IServiceCollection services)

实际上你可以设置并返回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);
}

official documentation中查看更多详细信息

© www.soinside.com 2019 - 2024. All rights reserved.