将现有的IServiceCollection和ILoggerFactory传递到.NET Core 2中的启动中

问题描述 投票:1回答:3

我有一个承载Web API的控制台应用程序。现在,我要将已配置的IServiceCollectionILoggerFactory传递给我的Startup

var serviceCollection = new ServiceCollection();
// Do some registrations here...

var loggerFactory = new LoggerFactory(); // Actually not created this way. Just an example.
loggerFactory.AddSomeStuff();

var host = WebHost.CreateDefaultBuilder()
    .UseKestrel()
    .ConfigureServices(collection =>
    {
        // I want to use my already configured serviceCollection.
        // I do not want to configure it here...
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        // I want to use my already configured ILoggerFactory.
        // I do not want to configure it here...
    })
    .UseStartup<Startup>()
    .Build();

基本上,我希望我的启动使用已创建的loggerFactoryserviceCollection。那可能吗?如果是这样,我该怎么办?

c# dependency-injection asp.net-core asp.net-core-2.0
3个回答
0
投票

WebHost的Build方法将ServiceCollection()类的实例实例化为方法变量,并将其传递给每个Action委托(示例:ConfigureService(Action<IServiceCollection>configureService))。似乎没有办法用自定义实例替换该实例,除非自己实现IWebHost(可能会引入各种问题)。此致。


0
投票

不可能:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#create-logs-in-the-startup-class

不支持在Startup.ConfigureServices方法中完成DI容器设置之前写日志:

  • 不支持将日志记录器注入到启动构造函数中。
  • 不支持将记录器注入到Startup.ConfigureServices方法签名中

出现此限制的原因是,日志记录取决于DI和配置,而配置又取决于DI。在ConfigureServices完成之前,不会设置DI容器。


-1
投票

您可以将ILoggerFactory的构造函数参数添加到您的Startup类构造函数。

然后您可以在ConfigureServices方法中使用它。

public class Startup
{
    readonly ILoggerFactory loggerFactory;

    public Startup(ILoggerFactory loggerFactory)
    {
        this.loggerFactory = loggerFactory;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Use it here
        loggerFactory.CreateLogger<..>();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.