如何在启动时启动服务 (`IServiceCollection`)
How to start a service (`IServiceCollection`) at startup
我有一个单例服务,我希望 运行 在启动时等待一些 Controller
通过依赖注入构建服务。
该服务处理来自服务总线的数据,它似乎没有正确依赖客户端流量。最干净的初始化方法是什么?
哦,在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)
{
呃 :)
通常您会正常实例化服务,然后将其引用传递给 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();
}
我有一个单例服务,我希望 运行 在启动时等待一些 Controller
通过依赖注入构建服务。
该服务处理来自服务总线的数据,它似乎没有正确依赖客户端流量。最干净的初始化方法是什么?
哦,在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)
{
呃 :)
通常您会正常实例化服务,然后将其引用传递给 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();
}