.NET Core3.0 Autofac注入

时间:2025-03-19 17:04:14

参考地址:https://docs.autofac.org/en/latest/examples/index.html

1. nuget :Autofac.Extensions.DependencyInjection  Autofac.Extras.DynamicProxy

2.

using System.IO;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting; namespace DL.Admin
{
public class Program
{
public static void Main(string[] args)
{
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:2020")
.UseStartup<Startup>();
});
}
}
}

3. 启动文件Startup.cs内部添加以下方法

 public void ConfigureContainer(ContainerBuilder builder)
{
//添加任何Autofac模块或注册。
//这是在ConfigureServices之后调用的,所以
//在此处注册将覆盖在ConfigureServices中注册的内容。
//在构建主机时必须调用“UseServiceProviderFactory(new AutofacServiceProviderFactory())”`否则将不会调用此。 builder.RegisterModule(new AutofacModuleRegister(Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath, new List<string>()
{ //批量构造函数注入
"DL.Service.dll",
})); builder.RegisterType<Log4netService>()
.As<ILogService>()
.PropertiesAutowired()//开始属性注入
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例 builder.RegisterType<JwtService>()
.As<ITokenService>()
.PropertiesAutowired()//开始属性注入
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例 }

3. 创建下面类,进行批量注入

using Autofac;
using Autofac.Extras.DynamicProxy;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Module = Autofac.Module; namespace DL.Utils.Autofac
{
public class AutofacModuleRegister : Module
{
public string RootPath { get; set; }
public List<string> DllFiles { get; set; }
public AutofacModuleRegister(string rootPath, List<string> dllFiles)
{
RootPath = rootPath;
DllFiles = dllFiles;
} protected override void Load(ContainerBuilder builder)
{
foreach (var dllFile in DllFiles)
{
var dllFilePath = Path.Combine(RootPath, dllFile);//获取项目绝对路径
builder.RegisterAssemblyTypes(Assembly.LoadFile(dllFilePath))//直接采用加载文件的方法
//.PropertiesAutowired()//开始属性注入
//.Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()//表示注册的类型,以接口的方式注册不包括IDisposable接口
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy,使用接口的拦截器,在使用特性 [Attribute] 注册时,注册拦截器可注册到接口(Interface)上或其实现类(Implement)上。使用注册到接口上方式,所有的实现类都能应用到拦截器。
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例
} ////拦截器
////builder.Register(c => new AOPTest());
////注入类
////builder.RegisterType<UsersService>().As<UsersIService>().PropertiesAutowired().EnableInterfaceInterceptors(); ////程序集注入
//var IRepository = Assembly.Load("DL.IRepository");
//var Repository = Assembly.Load("DL.Repository");
//Assembly.GetExecutingAssembly();
////根据名称约定(仓储层的接口和实现均以Repository结尾),实现服务接口和服务实现的依赖
//builder.RegisterAssemblyTypes(IRepository, Repository)
// .Where(t => t.Name.EndsWith("Repository"))
// .AsImplementedInterfaces(); }
}
}

  4. Startup.cs的ConfigureServices 方法添加

 services.AddControllersWithViews()
.AddControllersAsServices();//这里要写

 4. Startup.cs的Configure 方法添加进行测试 

            using (var container = host.Services.CreateScope())
{
//ICacheService phone = container.ServiceProvider.GetService<ICacheService>();
//phone.Set<string>("1", "123");
ILogService log = container.ServiceProvider.GetService<ILogService>();
log.Debug(typeof(string), "mesg", new[] { "1", "2" }); //var str = phone.Get<string>("1"); IService.SysIservice.ISysAdminService sysAdminService = container.ServiceProvider.GetService<IService.SysIservice.ISysAdminService>(); var list = sysAdminService.GetListAsync();
}