using ASC.Common.Caching; using ASC.Common.Logging; using ASC.Core.Common.Hosting.Interfaces; using ASC.Core.Common.Hosting; using ASC.EventBus; using ASC.EventBus.Abstractions; using ASC.EventBus.RabbitMQ; using Autofac; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using ASC.Common; using ASC.EventBus.MemoryCache; namespace ASC.Api.Core.Extensions { public static class ServiceCollectionExtension { public static void AddEventBus(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton(); var rabbitMQConfiguration = configuration.GetSection("RabbitMQ").Get(); if (rabbitMQConfiguration != null) { services.AddSingleton(sp => { var cfg = sp.GetRequiredService(); var settings = cfg.GetSection("RabbitMQ").Get(); var logger = sp.GetRequiredService>(); var factory = new ConnectionFactory() { HostName = settings.HostName, DispatchConsumersAsync = true }; if (!string.IsNullOrEmpty(settings.UserName)) { factory.UserName = settings.UserName; } if (!string.IsNullOrEmpty(settings.Password)) { factory.Password = settings.Password; } var retryCount = 5; if (!string.IsNullOrEmpty(cfg["core:eventBus:connectRetryCount"])) { retryCount = int.Parse(cfg["core:eventBus:connectRetryCount"]); } return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); services.AddSingleton(sp => { var cfg = sp.GetRequiredService(); var rabbitMQPersistentConnection = sp.GetRequiredService(); var iLifetimeScope = sp.GetRequiredService(); var logger = sp.GetRequiredService>(); var eventBusSubcriptionsManager = sp.GetRequiredService(); var subscriptionClientName = "backup"; if (!string.IsNullOrEmpty(cfg["core:eventBus:subscriptionClientName"])) { subscriptionClientName = cfg["core:eventBus:subscriptionClientName"]; } var retryCount = 5; if (!string.IsNullOrEmpty(cfg["core:eventBus:connectRetryCount"])) { retryCount = int.Parse(cfg["core:eventBus:connectRetryCount"]); } return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount); }); } else { services.AddSingleton(sp => { var cfg = sp.GetRequiredService(); var iLifetimeScope = sp.GetRequiredService(); var logger = sp.GetRequiredService>(); var eventBusSubcriptionsManager = sp.GetRequiredService(); return new EventBusMemoryCache(logger, iLifetimeScope, eventBusSubcriptionsManager); }); } } public static void AddActivePassiveHostedService(this IServiceCollection services) where T : class, IHostedService { var diHelper = new DIHelper(services); diHelper.TryAdd, RegisterInstanceDao>(); diHelper.TryAdd, RegisterInstanceManager>(); services.AddHostedService>(); diHelper.TryAdd(); services.AddHostedService(); } } }