【问题标题】:Is it possible to inject dependency to parameterless constructor?是否可以将依赖项注入无参数构造函数?
【发布时间】:2021-04-20 02:22:42
【问题描述】:

在 X 类中,我有以下代码块,并且我面临“'QueueConsumer' 必须是具有公共无参数构造函数的非抽象类型才能将其用作参数 'TConsumer'泛型类型或方法 'ConsumerExtensions.Consumer(IReceiveEndpointConfigurator, Action)'”错误。

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

在 QueueConsumer 中,我使用 IConfiguration 类和依赖注入。我知道,如果我使用空构造函数,我不会看到上面的错误,但是我不能使用 IConfiguration。这是我的 QueueConsumer 类:

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

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

【问题讨论】:

  • ReceiveEndpointConsumer 是什么?如果你在这里使用某种框架,你应该说出它是什么。
  • 序列化有时需要无参数构造函数。如果需要,可以创建一个私有的无参数构造函数并设置一些断点以查看注入的构造函数是否被命中。
  • 您可以使用属性注入,但您没有告诉我们您使用的是什么 DI 框架(如果有的话)。看起来像来自 .net/asp.net 核心的原生版本?
  • 对不起,我是 .NET 的新手,没有使用任何特定的 DI 框架。 ReceiveEndpointConsumer 来自 Masstransit

标签: c# dependency-injection masstransit


【解决方案1】:

Masstransit 支持消费者factories

取自以上链接:

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 框架。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2019-04-20
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多