How to inject a reference to a specific IHostedService implementation?

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

    Based on your answers, I made a helpful extension method. It allows to register an IHostedService with another interface.

    The other interface doesn't need to implement IHostedService, so you don't expose the StartAsync() and StopAsync() methods

    public static class ServiceCollectionUtils
    {
        public static void AddHostedService(this IServiceCollection services)
            where TService : class
            where TImplementation : class, IHostedService, TService
        {
            services.AddSingleton();
            services.AddHostedService>();
        }
    
        private class HostedServiceWrapper : IHostedService
        {
            private readonly IHostedService _hostedService;
    
            public HostedServiceWrapper(TService hostedService)
            {
                _hostedService = (IHostedService)hostedService;
            }
    
            public Task StartAsync(CancellationToken cancellationToken)
            {
                return _hostedService.StartAsync(cancellationToken);
            }
    
            public Task StopAsync(CancellationToken cancellationToken)
            {
                return _hostedService.StopAsync(cancellationToken);
            }
        }
    }
    

提交回复
热议问题