ASP.NET Core搭建多層網站架構【9.1-使用Autofac代替原生的依賴注入】

2020/01/30, ASP.NET Core 3.1, VS2019, Autofac.Extensions.DependencyInjection 5.0.1html

摘要:基於ASP.NET Core 3.1 WebApi搭建後端多層網站架構【9.1-使用Autofac代替原生的依賴注入】
使用Autofac替換原生的依賴注入git

文章目錄github

此分支項目代碼json

本章節介紹了使用Autofac代替原生的依賴注入,使用Autofac爲的是後面配合Castle.Core作AOP動態代理後端

添加包引用

MS.WebApi應用程序中添加Autofac.Extensions.DependencyInjection包:架構

<ItemGroup>
  <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />
</ItemGroup>

注意此處包和下一章節會用到Autofac.Extras.DynamicProxy包二者須要配合使用,詳情看下一章節app

替換DI容器

修改Program.cs

打開Program.cs類,給Host.CreateDefaultBuilder(args)添加代碼.UseServiceProviderFactory(new AutofacServiceProviderFactory())

注意須要添加引用:using Autofac.Extensions.DependencyInjection;ide

修改Startup.cs

在Startup類中,註釋掉本來的構造函數,並添加如下代碼:函數

public ILifetimeScope AutofacContainer { get; private set; }

public Startup(IWebHostEnvironment env)
{
    // In ASP.NET Core 3.0 `env` will be an IWebHostingEnvironment, not IHostingEnvironment.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
//添加autofac的DI配置容器
public void ConfigureContainer(ContainerBuilder builder)
{

}

注意要添加using Autofac;引用。測試

完成後以下圖所示:

至此,Autofac替換原生依賴注入就完成了,能夠在新加的ConfigureContainer方法中使用Autofac的方法註冊服務。

使用

咱們把以前寫的IBaseService、IRoleService兩個服務改爲Autofac註冊試試。
先把以前的註冊刪掉:

services.AddScoped<IBaseService, BaseService>();
services.AddScoped<IRoleService, RoleService>();

在ConfigureContainer中添加如下代碼:

//註冊IBaseService和IRoleService接口及對應的實現類
builder.RegisterType<BaseService>().As<IBaseService>().InstancePerLifetimeScope();
builder.RegisterType<RoleService>().As<IRoleService>().InstancePerLifetimeScope();

完成後,啓動項目,打開Postman測試接口,發現服務都是正常被調用的:

相關文章
相關標籤/搜索