简体   繁体   中英

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

I have a console-application that hosts a Web API. Now I want to pass an already configured IServiceCollection and ILoggerFactory to my 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();

Basically I want my Startup to use my already created loggerFactory and serviceCollection . Is that possible? And if so, how do I do it?

The WebHost's Build method is instantiating an instance of ServiceCollection() class as a method variable and it is passed to every Action delegate (example: ConfigureService(Action<IServiceCollection>configureService)) . It seems there is no way of replacing that with custom one except making own implementation of IWebHost (which can introduce all sorts of problems). Regards.

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

Writing logs before completion of the DI container setup in the Startup.ConfigureServices method is not supported:

  • Logger injection into the Startup constructor is not supported.
  • Logger injection into the Startup.ConfigureServices method signature is not supported

The reason for this restriction is that logging depends on DI and on configuration, which in turns depends on DI. The DI container isn't set up until ConfigureServices finishes.

You can add a constructor parameter for ILoggerFactory to your Startup class constructor.

Then you can use it in the ConfigureServices method.

public class Startup
{
    readonly ILoggerFactory loggerFactory;

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

    public void ConfigureServices(IServiceCollection services)
    {
        // Use it here
        loggerFactory.CreateLogger<..>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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