MassTransit 6.0 中使用 Autofac 的 NLog?

NLog with Autofac in MassTransit 6.0?

由于以下原因,我的消费者无法从 Autofac 实例化:

Cannot resolve parameter 'Microsoft.Extensions.Logging.Logger1[MyConsumer] logger' of constructor 'Void .ctor(MyService, Microsoft.Extensions.Logging.Logger1[MyConsumer])'.

除 MassTransit 消费者外,ILoggers 在其他 class 中解析得很好;我认为这是 LogContext.ConfigureCurrentLogContext(); 的问题。和操作顺序。以下是代码,为简洁起见进行了编辑:

ContainerBuilder builder = new ContainerBuilder(); // Autofac

builder.RegisterType<LoggerFactory>()
                         .As<ILoggerFactory>()
                         .SingleInstance();

builder.RegisterGeneric(typeof(Logger<>))
                         .As(typeof(ILogger<>))
                         .SingleInstance();

builder.RegisterAssemblyTypes() // load up all services, yada yada

// what to pass here? I'm inside an unbuilt Autofac Container at this point. There is no ILoggerFactory until the Container is built!
LogContext.ConfigureCurrentLogContext(); // configure MassTransit logging

builder.AddMassTransit(x => 
            {
                x.AddConsumers(Assembly.GetEntryAssembly());

                x.AddBus(bus => MassTransit.Bus.Factory.CreateUsingRabbitMq(config =>
                {
                    config.ConfigureEndpoints(bus); // wire-up consumers discovered by the AddConsumers() call above
                }));
            });

Container = builder.Build(); // now build the container

// add NLog
IServiceProvider serviceProvider = new AutofacServiceProvider(Container); // this requires a built Container!
ILoggerFactory loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddNLog();

我应该注意到,在 MassTransit 中登录实际上是有效的;我看到了关于队列和消息的各种调试输出。但是消费者不会出于任何原因实例化。如果我尝试手动 Resolve<ILogger<MyConsumer>>() 我会得到一个 ILogger,但 MassTransit 似乎有问题。

编辑:通过 VS 输出的完整错误消息:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyConsumer' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.Extensions.Logging.Logger 1[MyConsumer] logger' of constructor 'Void .ctor(MyService, Microsoft.Extensions.Logging.Logger`1[MyConsumer])'.*

包版本:

Cannot resolve parameter Microsoft.Extensions.Logging.Logger 1[MyConsumer] logger

此错误消息表示 Autofac 无法找到已注册的 Logger<MyConsumer>。如果您查看您的注册,您注册的是 ILogger<> 而不是 Logger<>。您应该将依赖项更改为 MyConsumer 中的接口版本,然后 autofac 会找到它。