多个AddHostedService dotnet核心

时间:2018-07-14 08:53:21

标签: asp.net-core .net-core

当我尝试注册多个 AddHostedService 时,仅在第一个

上调用方法 StartAsync
services.AddHostedService<HostServiceBox>(); // StartAsync is called
services.AddHostedService<HostServiceWebSocket>(); // DO NOT WORK StartAsync not called
services.AddHostedService<HostServiceLogging>(); // DO NOT WORK StartAsync not called

有什么主意吗?

感谢帮助

2 个答案:

答案 0 :(得分:0)

托管服务通常是一项任务,因此我将以单例方式进行。

// Hosted Services
services.AddSingleton<IHostedService, HttpGetCurrencyPairRequestSyncingService>();
services.AddSingleton<IHostedService, HttpPostCurrencyPairRequestSyncingService>();

在我上课的时候,

public class CurrencyPairCacheManagementService : BaseHostedService<CurrencyPairCacheManagementService>
        , ICurrencyPairCacheManagementService, IHostedService, IDisposable
    {
        private ICurrencyPairService _currencyPairService;
        private IConnectionMultiplexer _connectionMultiplexer;

        public CurrencyPairCacheManagementService(IConnectionMultiplexer connectionMultiplexer,
            IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _currencyPairService = serviceProvider.GetService<CurrencyPairService>();
            _connectionMultiplexer = connectionMultiplexer;

            InitializeCache(serviceProvider);
        }

        /// <summary>
        /// Operation Procedure for CurrencyPair Cache Management.
        ///
        /// Updates every 5 seconds.
        ///
        /// Objectives:
        /// 1. Pull the latest currency pair dataset from cold storage (DB)
        /// 2. Cross reference checking (MemoryCache vs Cold Storage)
        /// 3. Update Currency pairs
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("CurrencyPairCacheManagementService is starting.");

            stoppingToken.Register(() => _logger.LogInformation("CurrencyPairCacheManagementService is stopping."));

            while (!stoppingToken.IsCancellationRequested)
            {
                var currencyPairs = _currencyPairService.GetAllActive();

                await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
            }

            _logger.LogWarning("CurrencyPairCacheManagementService background task is stopping.");
        }

        public void InitializeCache(IServiceProvider serviceProvider)
        {
            var currencyPairs = _currencyPairService.GetAllActive();

            // Load them individually to the cache.
            // This way, we won't have to update the entire collection if we were to remove, update or add one.
            foreach (var cPair in currencyPairs)
            {
                // Naming convention => PREFIX + CURRENCYPAIRID
                // Set the object into the cache

            }
        }

        public Task InproPair(CurrencyPair currencyPair)
        {
            throw new NotImplementedException();
        }
    }

ExecuteAsync首先被击中,然后继续执行您想要的操作。您可能还希望删除我拥有的泛型声明,因为我的基类与泛型一起运行(如果您不使用泛型来运行托管的服务基类,那么我认为您无需显式继承IHostedService和IDisposable)。

答案 1 :(得分:0)

下面的代码可以工作 我通过创建一个助手来解决这个问题

@ statup.cs

public void ConfigureServices(IServiceCollection services)
        {
            JwtBearerConfiguration(services);

            services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowAnyOrigin()
                    .AllowCredentials();
            }));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ;


            services.AddSignalR();

            services.AddHostedService<HostServiceHelper>(); // <===== StartAsync is called

        }

@ HostServiceHelper.cs

    public class HostServiceHelper : IHostedService
    {
        private static IHubContext<EngineHub> _hubContext;

        public HostServiceHelper(IHubContext<EngineHub> hubContext)
        {
            _hubContext = hubContext;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            {
                Task.Run(() => ServiceWebSocket(), cancellationToken);

                Task.Run(() => ServiceBox(), cancellationToken);

                Task.Run(() => ServiceLogging(), cancellationToken);

            }, cancellationToken);
        }

        public void ServiceLogging()
        {
        // your own CODE
         }

        public void ServiceWebSocket()
        {
 // your own CODE
        }

        public void ServiceBox()
        {
            // your own CODE
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            //Your logical
            throw new NotImplementedException();
        }
    }