使用第三方依賴注入
除了使用內(nèi)置的依賴注入模塊,我們還可以直接使用一些第三方的依賴注入框架,例如Autofac, StructureMap。
這里我們來使用StructureMap來替換當前的內(nèi)置的依賴注入框架。
首先我們需要先添加程序集引用。
PM> Install-Package StructureMap.Microsoft.DependencyInjection
然后我們來修改Program.cs文件,代碼如下
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using StructureMap; using System; namespace DIInConsoleApp { class Program { static void Main(string[] args) { var services = new ServiceCollection().AddLogging(); var container = new Container(); container.Configure(config => { config.Scan(_ => { _.AssemblyContainingType(typeof(Program)); _.WithDefaultConventions(); }); config.Populate(services); }); var serviceProvider = container.GetInstance<IServiceProvider>(); serviceProvider.GetService<ILoggerFactory>().AddConsole(LogLevel.Debug); var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>(); logger.LogInformation("Start application."); var bar = serviceProvider.GetService<IBarService>(); bar.DoSomeRealWork(); logger.LogInformation("All done!"); Console.Read(); } } }
代碼解釋
最終效果
運行程序,代碼和之前的效果一樣
info: DIInConsoleApp.Program[0]
Start application.
info: DIInConsoleApp.FooService[0]
Doing the thing 0
info: DIInConsoleApp.FooService[0]
Doing the thing 1
info: DIInConsoleApp.FooService[0]
Doing the thing 2
info: DIInConsoleApp.FooService[0]
Doing the thing 3
info: DIInConsoleApp.FooService[0]
Doing the thing 4
info: DIInConsoleApp.FooService[0]
Doing the thing 5
info: DIInConsoleApp.FooService[0]
Doing the thing 6
info: DIInConsoleApp.FooService[0]
Doing the thing 7
info: DIInConsoleApp.FooService[0]
Doing the thing 8
info: DIInConsoleApp.FooService[0]
Doing the thing 9
info: DIInConsoleApp.Program[0]
All done!
本篇源代碼 (本地下載)
總結
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com