是否可以将依赖项注入无参数构造函数?

Is it possible to inject dependency to parameterless constructor?

在 X class 中,我有以下代码块,我面临着“'QueueConsumer' 必须是具有 [=26= 的非抽象类型] 无参数构造函数,以便在泛型类型或方法 'ConsumerExtensions.Consumer(IReceiveEndpointConfigurator, Action<IConsumerConfigurator>)' 中将其用作参数 'TConsumer'”错误。

cfg =>
{
     cfg.Host(ServiceBusConnectionString);
     cfg.ReceiveEndpoint(router.Name, e =>
     {
         e.Consumer<QueueConsumer>(); // I got the error in this line
     });
 }

在 QueueConsumer 中,我将 IConfiguration class 与依赖项注入一起使用。我知道,如果我使用空构造函数,我不会看到上述错误,但我无法使用 IConfiguration。这是我的 QueueConsumer class:

public class QueueConsumer : IConsumer<TransferMessage>
{
    public readonly IConfiguration _configuration;
    public QueueConsumer(IConfiguration configuration)
    {
        _configuration = configuration;
    } 

那么,您知道如何避免这个问题吗?我如何使用无参数构造函数的依赖注入?

Masstransit 支持 factories 消费者:

取自以上link:

cfg.ReceiveEndpoint("order-service", e =>
{
    // delegate consumer factory
    e.Consumer(() => new SubmitOrderConsumer());

    // another delegate consumer factory, with dependency
    e.Consumer(() => new LogOrderSubmittedConsumer(Console.Out));

    // a type-based factory that returns an object (specialized uses)
    var consumerType = typeof(SubmitOrderConsumer);
    e.Consumer(consumerType, type => Activator.CreateInstance(consumerType));
});

所以你可以在这里注入任何你想要的依赖。您还应该能够使用您想要的任何 DI 框架 in/as 这样的工厂方法。

但是,如果您正在使用 ASP.Net Core DI,请阅读以下内容以了解 MassTransit 内置的集成: https://masstransit-project.com/usage/configuration.html#asp-net-core