簡體   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