繁体   English   中英

将现有的 IServiceCollection 和 ILoggerFactory 传递给 .NET Core 2 中的 Startup

[英]Pass existing IServiceCollection and ILoggerFactory to Startup in .NET Core 2

我有一个托管 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();

基本上我希望我的 Startup 使用我已经创建的loggerFactoryserviceCollection 这可能吗? 如果是这样,我该怎么做?

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

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

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

  • 不支持将 Logger 注入到 Startup 构造函数中。
  • 不支持将 Logger 注入 Startup.ConfigureServices 方法签名

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

您可以将 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<..>();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM