C# Aspnet core 5.0在startup.cs构造函数中注入依赖项
我正在尝试使用以下方法将参数添加到Asp.net core中启动类的构造函数中: 然而,这对我不起作用。 这是我的C代码: 当我执行此操作时,会出现以下异常: System.InvalidOperationException:“在尝试激活“Spike.Run.Launcher.ILauncherContext”时,无法解析类型“Spike.Run.Launcher.ILauncherContext”的服务。”参考 使用通用主机(IHostBuilder)时,只能将以下服务类型注入启动构造函数:C# Aspnet core 5.0在startup.cs构造函数中注入依赖项,c#,asp.net-core,dependency-injection,C#,Asp.net Core,Dependency Injection,我正在尝试使用以下方法将参数添加到Asp.net core中启动类的构造函数中: 然而,这对我不起作用。 这是我的C代码: 当我执行此操作时,会出现以下异常: System.InvalidOperationException:“在尝试激活“Spike.Run.Launcher.ILauncherContext”时,无法解析类型“Spike.Run.Launcher.ILauncherContext”的服务。”参考 使用通用主机(IHostBuilder)时,只能将以下服务类型注入启动构造函数:
- IWebHostEnvironment
- I外部环境
- I配置
Configure
方法之前,大多数服务都不可用。
强调我的
改用配置方法
public AppAStartup(IConfiguration configuration) {
Configuration = configuration;
}
public void Configure(IApplicationBuilder app, ..., ILauncherContext launcherContext) {
//access launcherContext here
//...
}
虽然将依赖项注入到启动的构造函数中是一件有趣的事情,但您有想要这样做的实际原因吗?有任何可能的情况吗?您不应该使用services.AddSingleton()
来添加依赖项吗?而不是自己创建对象。
#region Constructors
public AppAStartup(IConfiguration configuration, ILauncherContext launcherContext)
{
Configuration = configuration;
this.launcherContext = launcherContext;
}
#endregion
public AppAStartup(IConfiguration configuration) {
Configuration = configuration;
}
public void Configure(IApplicationBuilder app, ..., ILauncherContext launcherContext) {
//access launcherContext here
//...
}