.Net Core 通過依賴注入和動態(tài)加載程序集實現(xiàn)宿主程序和接口實現(xiàn)類庫完全解構(gòu)
網(wǎng)上很多.Net Core依賴注入的例子代碼,例如再宿主程序中要這樣寫:
services.AddTransient<Interface1, Class1>();
其中Interface1是接口,Class1是接口的實現(xiàn)類,一般我們會將接口項目和實現(xiàn)類項目分開成兩個項目以實現(xiàn)解耦。
但這段代碼卻要求宿主程序要引用實現(xiàn)類項目,所以這里的解構(gòu)實現(xiàn)的并不徹底,要完全解耦就是要實現(xiàn)宿主程序不引用實現(xiàn)類項目。
或者把注入的代碼改成這樣:
services.Add(new ServiceDescriptor(serviceType: typeof(Interface1), implementationType: Type.GetType("ClassLibrary1.Class1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"), lifetime: ServiceLifetime.Transient));
其實這段代碼也要求宿主類引用實現(xiàn)類庫項目,不然運行會出錯,只有采用動態(tài)加載程序集的方式才能實現(xiàn)宿主程序不引用實現(xiàn)類:
var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"C:\Users\pesu\source\repos\DynamicLoadDependencyInjectionConsoleApp\ClassLibrary1\bin\Debug\netcoreapp2.0\ClassLibrary1.dll");
上面代碼將實現(xiàn)類庫程序集動態(tài)加載到宿主程序,然后將注入的代碼改成這樣:
services.Add(new ServiceDescriptor(serviceType: typeof(Interface1), implementationType: myAssembly.GetType("ClassLibrary1.Class1"), lifetime: ServiceLifetime.Transient));
其中ClassLibrary1.Class1是Interface1的實現(xiàn)類,完整代碼如下:
using InterfaceLibrary; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Runtime.Loader; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"C:\Users\pesu\source\repos\DynamicLoadDependencyInjectionConsoleApp\ClassLibrary1\bin\Debug\netcoreapp2.0\ClassLibrary1.dll"); IServiceCollection services = new ServiceCollection(); //注入 services.AddTransient<ILoggerFactory, LoggerFactory>(); services.Add(new ServiceDescriptor(serviceType: typeof(Interface1), implementationType: myAssembly.GetType("ClassLibrary1.Class1"), lifetime: ServiceLifetime.Transient)); //構(gòu)建容器 IServiceProvider serviceProvider = services.BuildServiceProvider(); //解析 serviceProvider.GetService<ILoggerFactory>().AddConsole(LogLevel.Debug); var cls = serviceProvider.GetService<Interface1>(); cls.Say(); Console.ReadKey(); } } }
輸出:

這有什么用呢?
浙公網(wǎng)安備 33010602011771號