asp.net core 5.0在startup.cs构造函数中注入依赖



我试图添加一个参数的构造函数的启动类在Asp.net core使用这个方法:https://mattmazzola.medium.com/asp-net-core-injecting-custom-data-classes-into-startup-classs-constructor-and-configure-method-7cc146f00afb

然而,这对我不起作用。下面是我的c#代码:

public class AppAProgram
{
#region Members
private IHostBuilder hostBuilder;
private IHost host;
#endregion
#region Constructors
public AppAProgram(string[] args)
{
this.hostBuilder = Host.CreateDefaultBuilder(args);
ILauncherContext launcherContext = new DummyLauncherContext();
this.hostBuilder.ConfigureServices((hostContext, services) => { services.AddSingleton<ILauncherContext>(launcherContext); });
this.hostBuilder.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<AppAStartup>(); });
this.host = hostBuilder.Build();
}
#endregion
public static void Main(string[] args)
{
AppAProgram appAProgram = new AppAProgram(args);    
appAProgram.Start();
}
public void Start()
{
this.host.Run();
}
}

下面是我为其添加注入参数的构造函数:

#region Constructors
public AppAStartup(IConfiguration configuration, ILauncherContext launcherContext)
{
Configuration = configuration;
this.launcherContext = launcherContext;
}
#endregion

当我这样做的时候,我得到这个异常:

系统。InvalidOperationException: '无法解析服务类型'Spike.Run.Launcher。尝试激活' spike . run . apppa . appastartup '.'

ReferenceStartup class

当使用通用主机(IHostBuilder)时,只有以下服务类型可以被注入到Startup构造函数中:

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

……

大多数服务在调用Configure方法之前是不可用的。

强调我的

使用Configure方法代替

public AppAStartup(IConfiguration configuration) {
Configuration = configuration;        
}
public void Configure(IApplicationBuilder app, ..., ILauncherContext launcherContext) {
//access launcherContext here
//...
}

相关内容

  • 没有找到相关文章

最新更新