我想在启动时运行一个单件服务,而不是等待某些Controller
通过依赖注入构建服务。
该服务处理来自服务总线的数据,似乎不依赖于客户端流量。初始化它的最简洁方法是什么?
答案 0 :(得分:1)
通常您会正常实例化服务,然后将其引用传递给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();
}
答案 1 :(得分:0)
哦,即使您不需要配置它,也只需在Startup.cs
中引用它。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Has message bus connection
services.AddSingleton<ISomeRespository, SomeRepository>();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(... ISomeRespository db)
{
Duh:)