【问题标题】:How to integrate Autofac with Asp.net core 2.2如何将 Autofac 与 Asp.net core 2.2 集成
【发布时间】:2019-08-25 20:22:51
【问题描述】:

我有以下指南: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) 是 return void

public void ConfigureServices(IServiceCollection services)

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

【问题讨论】:

  • 只需将void 替换为IServiceProvider
  • 确实,它有效@John

标签: c# asp.net-core dependency-injection .net-core autofac


【解决方案1】:

在您的解决方案中,您在 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查看更多详情

【讨论】:

  • 虽然我正要发布基本相同的内容,但您可能希望在您的答案中添加一些文本以解释其工作原理,即使它只是文档的引用(和链接): )
  • 这与 Autofac 的教程完全一样。最主要的是我们可以更改 ConfigService 函数的声明以返回 IServiceProvider
猜你喜欢
  • 2019-07-19
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多