c# - 如何将 Autofac 与 Asp.net core 2.2 集成

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

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

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

最佳答案

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

关于c# - 如何将 Autofac 与 Asp.net core 2.2 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55509836/

相关文章:

c# - 单元测试是否使 Debug.Assert() 变得不必要?

c# - 在 C++ 中使用 constraint_handlers

c# - C# 中的引用继承

linux - postgres用户的很多tracepath命令

c# - 看似循环依赖导致 CaSTLe Windsor 出现问题

c# - 采用 WF 的 Web 应用程序的最佳设计是什么?

asp.net-core - .Net Core 仅在上传文件时被 CORS 策略错误阻止

asp.net-core - 如何在 ASP.NET Core 中获取中间件列表

symfony - FOSRestBundle Controller 作为服务无法正常工作

dependency-injection - 使用依赖注入(inject)将 Feathers 应用程序对象传递给 TypeGraphQL