# 一、创建类库 Extensions,并且安装 Autofac 依赖
安裝两个 Nugget 包:Autofac.Extensions.DependencyInjection
和 Autofac.Extras.DynamicProxy
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0"/>
<PackageReference Include="Autofac.Extras.DynamicProxy" Version="6.0.0"/>
</ItemGroup>
1
2
3
4
2
3
4
# 二、封装 AutofacModuleRegister.cs
public class AutofacModuleRegister : Autofac.Module
{
// private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
#region 带有接口层的服务注入
var servicesDllFile = Path.Combine(basePath, "Services.dll");
var repositoryDllFile = Path.Combine(basePath, "Repository.dll");
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
{
var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹";
// log.Error(msg);
throw new Exception(msg);
}
// builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
builder.RegisterGeneric(typeof(BaseRepository<,>)).As(typeof(IBaseRepository<,>)).InstancePerDependency();//注册仓储
// 获取 Service.dll 程序集服务,并注册
var assemblyServices = Assembly.LoadFrom(servicesDllFile);
builder.RegisterAssemblyTypes(assemblyServices)
.AsImplementedInterfaces()
.InstancePerDependency()
.EnableInterfaceInterceptors();//引用Autofac.Extras.DynamicProxy;
//.InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
// 获取 Repository.dll 程序集服务,并注册
var assemblyRepository = Assembly.LoadFrom(repositoryDllFile);
builder.RegisterAssemblyTypes(assemblyRepository)
.AsImplementedInterfaces()
.InstancePerDependency();
#endregion
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 三、在 Program 中 Autofac 服务工厂
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
1
2
3
4
5
6
7
2
3
4
5
6
7
# 四、在 Startup 中
// 注意,要在 Program 中 添加 AutofacServiceProviderFactory
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModuleRegister());
}
1
2
3
4
5
2
3
4
5