[英]How to get Microsoft.Extensions.Logging<T> in console application using Serilog and AutoFac?
在 ASP.NET Core 應用程序中,我們有常見的 BL 類,它們會進入到構造函數中:
Microsoft.Extensions.Logging.ILogger<Foo>
在 ASP.NET Core 中,ASP.NET 的內部基礎結構處理通過LoggerFactory
獲取 ILogger。
我們現在想在控制台應用程序中重用這些 BL 類(用於異步作業),我們如何設置AutoFac和 Serilog 以在LoggerFactory
不存在的環境中注入Microsoft.Extensions.Logging.ILogger<T>
?
Microsoft.Extensions.Logging
(參見源代碼)不是 ASP.NET Core 的一部分,可以獨立於它運行。 您需要做的就是注冊ILoggerFactory
和ILogger<>
接口。
Logger<T>
使用ILoggerFactory
來實例化實際的記錄器。
在控制台應用程序中使用 Logging 擴展時,建議仍然使用IServiceCollection
,因為這允許您使用IServiceCollection
擴展方法來注冊支持此模式的所有包。
var services = new ServiceCollection();
services.AddLogging();
// Initialize Autofac
var builder = new ContainerBuilder();
// Use the Populate method to register services which were registered
// to IServiceCollection
builder.Populate(services);
// Build the final container
IContainer container = builder.Build();
這是推薦的方法,因為您不必詳細考慮需要為具有Microsoft.Extensions.DependencyInjection
集成支持的庫注冊哪些類。
但是當然你也可以手動注冊它,但是當Microsoft.Extensions.Logging
庫(添加新的依賴項)發生變化時,你不會得到它,首先必須弄清楚或挖掘源代碼才能找到錯誤。
builder.RegisterType<LoggerFactory>()
.As<ILoggerFactory>()
.SingleInstance();
builder.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>))
.SingleInstance();
剩下的就是在容器構建之后或應用程序啟動之前注冊記錄器類型:
var loggerFactory = container.Resolve<ILoggerFactory>();
loggerFactory.AddConsole()
.AddSerilog();
並像往常一樣在您的服務中注入ILogger<MyService>
。
如果您想直接在 Autofac 上手動注冊 ir,我會推薦一種稍微不同的方法:
private static void ConfigureLogging(ILoggingBuilder log)
{
log.ClearProviders();
log.SetMinimumLevel(LogLevel.Error);
log.AddConsole();
}
private static void ConfigureContainer(ContainerBuilder builder)
{
builder.Register(handler => LoggerFactory.Create(ConfigureLogging))
.As<ILoggerFactory>()
.SingleInstance()
.AutoActivate();
builder.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>))
.SingleInstance();
// other registrations
}
這在你的主要啟動代碼上:
var containerBuilder = new ContainerBuilder();
ConfigureContainer(containerBuilder);
var container = containerBuilder.Build();
var serviceProvider = new AutofacServiceProvider(container);
// you can use either the built container or set the serviceProvider onto the library you are using.
在控制台應用程序 Main 方法中
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
IConfigurationRoot configuration = builder.Build();
var serviceProvider = new ServiceCollection()
.AddDbContext<MyDbContext>(optionns => optionns.UseSqlServer(configuration.GetConnectionString("connectionString")))
.AddSingleton(typeof(ILogger<>), typeof(Logger<>))
.AddLogging()
.BuildServiceProvider();
MyDbContext _context = serviceProvider.GetService<MyDbContext>();
var _logger = serviceProvider.GetService<ILogger<YourClass>>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.