【发布时间】:2016-08-15 13:39:17
【问题描述】:
我有一个单例服务,我想在启动时运行,而不是等待一些 Controller 通过依赖注入构造服务。
服务处理来自服务总线的数据,它似乎没有正确依赖客户端流量。初始化它的最干净的方法是什么?
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api asp.net-core esb
我有一个单例服务,我想在启动时运行,而不是等待一些 Controller 通过依赖注入构造服务。
服务处理来自服务总线的数据,它似乎没有正确依赖客户端流量。初始化它的最干净的方法是什么?
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api asp.net-core esb
通常你通常实例化服务,然后将它的引用传递给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();
}
【讨论】:
SomeRepository 有自己的依赖项(消息总线)
IServiceProvider,并在Configure中调用它
app.RequestService<ISomeRepository>(),但热身扩展感觉最好
哦,在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)
{
呃 :)
【讨论】: