How to inject a reference to a specific IHostedService implementation?

后端 未结 6 2144
半阙折子戏
半阙折子戏 2020-12-03 10:43

My web app has a background service that listens to a service bus. Based on the docs, it looks like the built-in way to run a background service is to implement IHoste

6条回答
  •  天涯浪人
    2020-12-03 11:11

    .net core now has a AddHostedService overload that lets you specify a factory function/method for resolving hosted services. This lets you specify your hosted service as a singleton and then inject it where necessary.

    Documentation says it's been available since .Net Core 3.x

    Arguably, one should analyze the architecture choices that led to this path to ensure that this route is actually required. But sometimes it may be necessary.

    AddHostedService(IServiceCollection, Func)
    

    Usage is

    services
       .AddSingleton()
       .AddHostedService(services => (MyServiceImplementation) services.GetService())
    ;
    

    If your IServiceContract inherits from IHostedService or you don't use an interface then the cast is unnecessary.

提交回复
热议问题