【问题标题】:How to start a service (`IServiceCollection`) at startup如何在启动时启动服务(`IServiceCollection`)
【发布时间】:2016-08-15 13:39:17
【问题描述】:

我有一个单例服务,我想在启动时运行,而不是等待一些 Controller 通过依赖注入构造服务。

服务处理来自服务总线的数据,它似乎没有正确依赖客户端流量。初始化它的最干净的方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api asp.net-core esb


    【解决方案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();
    }
    

    【讨论】:

    • 我唯一不喜欢的是“传入配置和依赖项”,因为我的SomeRepository 有自己的依赖项(消息总线)
    • 好吧,将其作为依赖项传递给 Configure 感觉很脏。当然你可以有一个预热扩展方法或IServiceProvider,并在Configure中调用它
    • 不错。我猜一个只有一件事要热身的懒惰编码员可以打电话给app.RequestService&lt;ISomeRepository&gt;(),但热身扩展感觉最好
    【解决方案2】:

    哦,在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)
    {
    

    呃 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2011-12-03
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多