我的消费者代码如下所示。发布事件时“没有为此对象定义无参数构造函数。”,抛出异常(请参阅下面的详细信息)。 我只使用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()
答案 0 :(得分:0)
这是一个实施问题。我使用以下方法解决了它以注册消费者。
conf.Consumer(consumer, serviceProvider.GetService);
serviceProvider is IServiceProvider
instead of
conf.Consumer(consumer, Activator.CreateInstance);