C# 将现有IServiceCollection和ILoggerFactory传递到.NET Core 2中的启动
我有一个托管Web API的控制台应用程序。现在,我想将已配置的C# 将现有IServiceCollection和ILoggerFactory传递到.NET Core 2中的启动,c#,dependency-injection,asp.net-core,asp.net-core-2.0,C#,Dependency Injection,Asp.net Core,Asp.net Core 2.0,我有一个托管Web API的控制台应用程序。现在,我想将已配置的IServiceCollection和iLogger工厂传递给我的启动 var serviceCollection = new ServiceCollection(); // Do some registrations here... var loggerFactory = new LoggerFactory(); // Actually not created this way. Just an example. loggerF
IServiceCollection
和iLogger工厂
传递给我的启动
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();
var servicecolection=new servicecolection();
//在这里做一些注册。。。
var loggerFactory=new loggerFactory();//其实不是这样创造的。只是一个例子。
loggerFactory.AddSomeStuff();
var host=WebHost.CreateDefaultBuilder()
.UseKestrel()
.ConfigureServices(集合=>
{
//我想使用已配置的serviceCollection。
//我不想在这里配置它。。。
})
.ConfigureLogging((hostingContext,logging)=>
{
//我想使用已配置的iLogger工厂。
//我不想在这里配置它。。。
})
.UseStartup()
.Build();
基本上,我希望我的初创公司使用我已经创建的
loggerFactory
和serviceCollection
。可能吗?如果是这样,我该怎么做?WebHost的构建方法将ServiceCollection()类的实例实例化为方法变量,并将其传递给每个操作委托(例如:ConfigureService(ActionconfigureService))
。似乎除了自己实现IWebHost(这可能会带来各种各样的问题)之外,没有办法用定制的替代。注意。您可以将iLogger工厂的构造函数参数添加到启动类构造函数中
然后可以在ConfigureServices方法中使用它
public class Startup
{
readonly ILoggerFactory loggerFactory;
public Startup(ILoggerFactory loggerFactory)
{
this.loggerFactory = loggerFactory;
}
public void ConfigureServices(IServiceCollection services)
{
// Use it here
loggerFactory.CreateLogger<..>();
}
}
公共类启动
{
只读iLogger工厂Logger工厂;
公共启动(iLogger工厂Logger工厂)
{
this.loggerFactory=loggerFactory;
}
public void配置服务(IServiceCollection服务)
{
//在这里使用它
loggerFactory.CreateLogger();
}
}
不可能:
不支持在Startup.ConfigureServices方法中完成DI容器设置之前写入日志:
- 不支持将记录器注入启动构造函数
- 不支持将记录器注入Startup.ConfigureServices方法签名
是的,它在ASP.NET Core 3.0中发生了更改。看见