本文主要介绍ASP .NET Core中依赖注入框架(DI)Autofac 4.0通过ContainerBuilder(Populate)配置和使用示例。

1、Autofac的配置

如果您需要更灵活地构建容器的方式,或者如果您需要实际存储对构建容器的引用,则需要跳过使用ConfigureContainer并在ConfigureServices期间注册所有内容。 这也是您为ASP.NET Core 1.0采用的途径方法。

1)通过Microsoft.Extensions.DependencyInjection包在ASP .NET Core应用程序中使用用Autofac。

在Nuget管理程序中,搜索'Autofac.Extensions.DependencyInjection' =》选中然后点击'安装'

2)使用ContainerBuilder(Populate)配置

Startup类的ConfigureServices方法中

  • 通过Populate将服务从IServiceCollection注册到ContainerBuilder
  • 直接在ContainerBuilder中注册服务。
  • Build容器(container)
  • 使用容器创建一个AutofacServiceProvider并将其返回。

2、在ASP .NET Core中使用ContainerBuilder(Populate)配置Autofac示例代码

public class Startup
{
  public Startup(IHostingEnvironment env)
  {
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    this.Configuration = builder.Build();
  }
  public IContainer ApplicationContainer { get; private set; }
  public IConfigurationRoot Configuration { get; private set; }
   //在ConfigureServices中注册依赖项。
   //在下面的Configure方法之前由运行时调用。
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
   //将服务添加到集合中。
    services.AddMvc();
    //创建 container builder.
    var builder = new ContainerBuilder();
     //注册依赖项,填充服务
     //集合,并构建容器。
     //
     //请注意,Populate基本上是添加内容的foreach
     //进入集合中的Autofac。 如果你注册
     //在Autofac之前的东西填充然后填充的东西
     // ServiceCollection可以覆盖那些东西; 如果你注册
     // AFTER填充这些注册可以覆盖的东西
     //在ServiceCollection中。 根据需要混合搭配。
    builder.Populate(services);
    builder.RegisterType<MyType>().As<IMyType>();
    this.ApplicationContainer = builder.Build();
   //根据容器创建IServiceProvider
    return new AutofacServiceProvider(this.ApplicationContainer);
  }
   //配置是添加中间件的位置。 这称之为
   // ConfigureServices。 您可以使用IApplicationBuilder.ApplicationServices
   //如果你需要从容器中解决问题。
  public void Configure(
    IApplicationBuilder app,
    ILoggerFactory loggerFactory,
    IApplicationLifetime appLifetime)
  {
      loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();
      app.UseMvc();
      //从Autofac.Extensions.DependencyInjection 4.3.0开始,AutofacDependencyResolver
      //实现IDisposable并将与应用程序容器一起处理
      //当应用程序停止并且WebHost处理它时
      //
      //在4.3.0之前,如果要处理已在中解析的资源
      //应用程序容器,注册“ApplicationStopped”事件。
      //如果直接引用容器,则只能执行此操作
      //所以它不适用于上面的ConfigureContainer机制。
      // appLifetime.ApplicationStopped.Register(()=>           this.ApplicationContainer.Dispose());
      //Cóng Autofac.Extensions.DependencyInjection 4.3.0 
  }
}

相关文档ASP .NET Core Autofac 4.0使用ConfigureContainer配置和示例代码

推荐文档

相关文档

大家感兴趣的内容

随机列表