我有一个单例服务,我想在启动时运行,而不是等待一些 Controller
通过依赖注入(inject)构建服务。
该服务处理来自服务总线的数据,它似乎并不完全依赖于客户端流量。最干净的初始化方法是什么?
最佳答案
通常您正常实例化服务,然后将它的引用传递给 AddSingleton()
方法。
var someRepository = new SomeRepository(/*pass in configuration and dependencies*/);
// pass instance of the already instantiated service
services.AddSingleton<ISomeRespository>(someRepository);
编辑
或者一个预热扩展方法:
public static class WarmupServiceProviderExtensions
{
public static void WarmUp(this IServiceProvider app)
{
// Just call it to resolve, no need to safe a reference
app.RequestService<ISomeRepository>();
}
}
在你的 Startup.cs 中
public void Configure(IServiceProvider app)
{
app.UseXyz(...);
// warmup/initailize your services
app.WarmUp();
}
关于c# - 如何在启动时启动服务 (`IServiceCollection` ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36785088/