基于ASP.NET Core 3.1 WebApi搭建後端多層網站架構【9.1-使用Autofac代替原生的依賴注入】
使用Autofac替換原生的依賴注入
2020/01/30, ASP.NET Core 3.1, VS2019, Autofac.Extensions.DependencyInjection 5.0.1
摘要:基于ASP.NET Core 3.1 WebApi搭建後端多層網站架構【9.1-使用Autofac代替原生的依賴注入】
文章目錄
此分支項目代碼
本章節介紹了使用Autofac代替原生的依賴注入,使用Autofac為的是後面配合Castle.Core做AOP動态代理
添加包引用
向
MS.WebApi
應用程式中添加
Autofac.Extensions.DependencyInjection
包:
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />
</ItemGroup>
注意此處包和下一章節會用到Autofac.Extras.DynamicProxy包兩者需要配合使用,詳情看下一章節
替換DI容器
修改Program.cs
打開
Program.cs
類,給
Host.CreateDefaultBuilder(args)
添加代碼
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
:
注意需要添加引用:
using Autofac.Extensions.DependencyInjection;
修改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測試接口,發現服務都是正常被調用的: