# DI NLog in .Net6 Console App ###### tags: `開發` `DI` `.Net6` ## 參考 * [Wire and inject NLog into .NET Core console app - stackoverflow](https://stackoverflow.com/questions/44838424/wire-and-inject-nlog-into-net-core-console-app) * [.Net Core Console 使用 DI](https://hackmd.io/@Wayne2021/SJwbrRsEo) * [Using NLog in a .NET 5 Console Application with Dependency Injection and send logs to AWS CloudWatch - Satish Yadav](https://dev.to/satish/using-nlog-in-a-net-5-console-application-with-dependency-injection-52mm) ## 實作 ### 安裝 ```bash! Install-Package NLog Install-Package NLog.Web.AspNetCore Install-Package Microsoft.Extensions.DependencyInjection ``` ### nlog.config 加上 nlog.config 檔案,並設定屬性「複製到輸出目錄:永遠複製」,或是加上以下程式碼。 ```csharp! <ItemGroup> <None Update="nlog.config" CopyToOutputDirectory="Always" /> </ItemGroup> ``` ### Program.cs ```csharp! // 1. 建立依賴注入的容器 var serviceCollection = new ServiceCollection(); // 2. 註冊服務 serviceCollection.AddTransient<DoSomething>(); // NLog serviceCollection.AddLogging(loggingBuilder => { // loggingBuilder.ClearProviders(); loggingBuilder.AddNLog("nlog.config"); }); // 建立依賴服務提供者 var serviceProvider = serviceCollection.BuildServiceProvider(); // 3. 執行主服務 serviceProvider.GetRequiredService<DoSomething>().Run(); ``` ### DoSomething.cs ```csharp! public class DoSomething { private ILogger<DoSomething> _Logger { get; } public DoSomething(ILogger<DoSomething> logger) { _Logger = logger; } public void Run() { _Logger.LogTrace("hello world"); } } ```