參考地址: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(); }