Autofa c не распознает мою IServiceCollection - PullRequest
1 голос
/ 13 июля 2020

Я создаю проект, основанный на eShopOnContainers архитектуре микросервисов

Я внес несколько изменений в program.cs и startup.cs в соответствии с. NET Core 3 +

Program.cs :

public static IHostBuilder CreateHostBuilder(IConfiguration configuration, string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())

Startup.cs:

// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you by the factory.
public void ConfigureContainer(ContainerBuilder builder)
{
     //configure autofac
     // Register your own things directly with Autofac, like:
     builder.RegisterModule(new MediatorModule());
     builder.RegisterModule(new ApplicationModule(Configuration));

 }

Сейчас в Startup.cs метод AddCustomIntegrations() Регистрирует IRabbitMQPersistentConnection, который возвращает DefaultRabbitMQPersistentConnection с IConnectionFactory настроенным

public static IServiceCollection AddCustomIntegrations(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<IIdentityService, IdentityService>();
        services.AddTransient<IVehicleManagementIntegrationEventService, VehicleManagementIntegrationEventService>();

        services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
            sp => (DbConnection c) => new IntegrationEventLogService(c));


        services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
        {
             var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();


             var factory = new ConnectionFactory()
             {
                 HostName = configuration["EventBusConnection"],
                 DispatchConsumersAsync = true
             };

             if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
             {
                 factory.UserName = configuration["EventBusUserName"];
             }

             if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
             {
                 factory.Password = configuration["EventBusPassword"];
             }

             var retryCount = 5;
             if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
             {
                 retryCount = int.Parse(configuration["EventBusRetryCount"]);
             }

             return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
        });
        
        return services;
    }
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
{
     var subscriptionClientName = configuration["SubscriptionClientName"];

      services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
      {
          var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
          var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
          var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
          var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();

           var retryCount = 5;
            if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
            {
                 retryCount = int.Parse(configuration["EventBusRetryCount"]);
            }

            return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
         });

     services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();

      return services;
}

Когда я запускаю приложение, я получаю следующую ошибку:

Autofac.Core.DependencyResolutionException: An exception was thrown while activating IFMS.GMT.BuildingBlocks.Infrastructure.Events.EventBusRabbitMQ.EventBusRabbitMQ -> IFMS.GMT.BuildingBlocks.Infrastructure.Events.EventBusRabbitMQ.DefaultRabbitMQPersistentConnection.
 ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'IFMS.GMT.BuildingBlocks.Infrastructure.Events.EventBusRabbitMQ.DefaultRabbitMQPersistentConnection' can be invoked with the available services and parameters:
Cannot resolve parameter 'RabbitMQ.Client.IConnectionFactory connectionFactory' of constructor 'Void .ctor(RabbitMQ.Client.IConnectionFactory, Microsoft.Extensions.Logging.ILogger`1[IFMS.GMT.BuildingBlocks.Infrastructure.Events.EventBusRabbitMQ.DefaultRabbitMQPersistentConnection], Int32)'.

Autofa c не могу найти службу, зарегистрированную с AddCustomIntegrations()

1 Ответ

1 голос
/ 13 июля 2020

I Перенес весь код из AddCustomIntegrations() и AddEventBus() в отдельный класс Module, который наследуется от класса Autofac.Module, и он работал

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterType<InMemoryEventBusSubscriptionsManager>()
               .As<IEventBusSubscriptionsManager>()
               .InstancePerLifetimeScope();


    builder.Register<IRabbitMQPersistentConnection>(fff => 
    {
        var logger = fff.Resolve<ILogger<DefaultRabbitMQPersistentConnection>>();
        
        var factory = new ConnectionFactory()
        {
            HostName = Configuration["EventBusConnection"],
            DispatchConsumersAsync = true
        };

        if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
        {
            factory.UserName = Configuration["EventBusUserName"];
        }

        if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
        {
            factory.Password = Configuration["EventBusPassword"];
        }

        var retryCount = 5;
        if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
        {
            retryCount = int.Parse(Configuration["EventBusRetryCount"]);
        }

            return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);

     });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...