How to inject a reference to a specific IHostedService implementation?

后端 未结 6 2139
半阙折子戏
半阙折子戏 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:31

    My little helper code in response to the excellent answer of jjxtra

        /// 
        /// Instead of calling service.AddHostedService you call this make sure that you can also access the hosted service by interface TImplementation
        /// https://stackoverflow.com/a/64689263/619465
        /// 
        /// The service collection
        public static void AddInjectableHostedService(this IServiceCollection services)
            where TService : class
            where TImplementation : class, IHostedService, TService
        {
            services.AddSingleton();
            services.AddSingleton(provider => provider.GetRequiredService());
            services.AddSingleton(provider => provider.GetRequiredService());
        }
    

    So this will allow you to register your IHostedService with

            services
                .AddInjectableHostedService();
    

    Where MyHostedServiceType off course implements some interface (IExposeSomething) with things that you want to expose to other types.

提交回复
热议问题