【问题标题】:How to Inject dependencies to a Consumer in Masstransit如何在 Masstransit 中向消费者注入依赖项
【发布时间】:2017-12-19 03:45:59
【问题描述】:

我的消费者代码如下所示。当发布事件“没有为此对象定义无参数构造函数”时,将引发异常(请参阅下面的详细信息)。 我只使用 Microsoft.Extensions.DependencyInjection 容器。如何注入依赖项?是否有此代码示例。

public class UserAddedConsumer : IConsumer<IUserCreated>
{
    IUserNotification notificationManager;
    ILogger<UserAddedConsumer> logger;
    public UserAddedConsumer(IUserNotification notificationManager, ILogger<UserAddedConsumer> logger)
    {
        this.notificationManager = notificationManager;
        this.logger = logger;
    }

    public Task Consume(ConsumeContext<IUserCreated> context)
    {
        logger.LogTrace("UserAddedConsumer - Userid: " + context.Message.Id);
        return notificationManager.UserCreated(context.Message.User);
    }
}
No parameterless constructor defined for this object., System.MissingMethodException: No parameterless constructor defined for this object.
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at System.Activator.CreateInstance(Type type)
  at MassTransit.ConsumeConfigurators.UntypedConsumerConfigurator1<>c__DisplayClass2_0.<.ctor>b__0()
  at MassTransit.Pipeline.ConsumerFactories.DelegateConsumerFactory1.<Send>d__21.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at MassTransit.Pipeline.Filters.ConsumerMessageFilter`2.<GreenPipes-IFilter<MassTransit-ConsumeContext<TMessage>>-Send>d__4.MoveNext()

【问题讨论】:

  • 至少显示你的端点配置代码。

标签: .net dependency-injection asp.net-core masstransit


【解决方案1】:

这是一个实施问题。我使用以下方法解决了它来注册消费者。

conf.Consumer(consumer, serviceProvider.GetService);
serviceProvider is IServiceProvider

instead of 
conf.Consumer(consumer, Activator.CreateInstance);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多