如何在启动时启动一个服务(`IServiceCollection`)

4

我有一个单例服务,我希望它在启动时运行,而不是等待一些控制器(Controller)通过依赖注入构造服务。

该服务从服务总线处理数据,似乎不应该依赖于客户端流量。最干净的初始化方式是什么?

2个回答

2

通常情况下,您正常地实例化服务,然后将其引用传递给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有自己的依赖项(消息总线)。 - KCD
将其作为依赖项传递给Configure感觉很不好。当然,您可以拥有一个预热扩展方法或IServiceProvider,并在Configure中调用它。 - Tseng
很好。我想一个只需要预热一件事情的懒惰的编码人员可以直接调用 app.RequestService<ISomeRepository>(),但是预热扩展感觉最好。 - KCD

1

即使您不需要配置它,也可以在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 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接