.NET Core3.0 Autofac注入
参考地址:https://docs.autofac.org/en/latest/examples/index.html
1. nuget :Autofac.Extensions.DependencyInjection Autofac.Extras.DynamicProxy
2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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内部添加以下方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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. 创建下面类,进行批量注入
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 40 41 42 43 44 45 46 47 48 49 50 | 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 方法添加
1 2 | services.AddControllersWithViews() .AddControllersAsServices(); //这里要写 |
4. Startup.cs的Configure 方法添加进行测试
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } |
彪悍的人生不需要解释,彪悍的代码不需要注释。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?