[英]Inject dependencies in Mediatr command handler
I am using Autofac and mediatr. 我正在使用Autofac和mediatr。 The flow is a message coming from
EventHub
and I process it and send it to respective command handlers. 该流是来自
EventHub
的消息,我处理它并将其发送给相应的命令处理程序。 I can inject few things from the api
projects perspective, using the builder
. 我可以使用
builder
从api
项目的角度注入一些东西。
builder.Register(ctx => {
var userInfo = ctx.Resolve<UserContextProvider>().GetUserInformation();
var connectionString = ResolveConnectionString(userInfo);
return new Repository(connectionString);
}).As<IRepository>();
As the messages are comming from event hub, I need to resolve those parameters dynamically. 当消息来自事件中心时,我需要动态地解决这些参数。 I have injected the
IComponentContext
into my message processor class and am trying to resolve the parameters. 我已将
IComponentContext
注入到我的消息处理器类中,并尝试解析参数。
_componentContext.Resolve<ActivityCommandHandler>(new NamedParameter("conStr", ConnectionString));
When I put breakpoint on the handler constructor I can see the conStr
when the above line is executed. 当我在处理程序构造函数上放置断点时,我可以在执行上面的行时看到
conStr
。
Is this the correct way of doing it ? 这是正确的做法吗?
When I send the command using _mediatr.send(mycommand)
I am getting the below exception. 当我使用
_mediatr.send(mycommand)
发送命令时,我得到以下异常。
None of the constructors found with
Autofac.Core.Activators.Reflection.DefaultConstructorFinder
on typeCommandHandlers.ActivityCommandHandler
can be invoked with the available services and parameters: Cannot resolve parameterSystem.String conStr
of constructorVoid .ctor(AutoMapper.IMapper, MediatR.IMediator, System.String)
与发现构造的无
Autofac.Core.Activators.Reflection.DefaultConstructorFinder
的类型CommandHandlers.ActivityCommandHandler
可以与提供的服务和参数来调用:无法解析参数System.String conStr
构造的Void .ctor(AutoMapper.IMapper, MediatR.IMediator, System.String)
My suggestion is not to use named-parameters. 我的建议是不要使用命名参数。
Wrap information in an object and register the object itself. 在对象中包装信息并注册对象本身。
Possible object structure: 可能的对象结构:
public class ConnectionConfiguration
{
public string ConnectionString { get; }
public ConnectionConfiguration(string connectionString) => ConnectionString = connectionString;
}
builder.Register(_ => new ConnectionConfiguration(ConnectionString));
Now inject that in your handler. 现在将其注入您的处理程序中。 No extra registration required which also doesn't work because the handlers are already registered to be resolved as open-generics as can be seen here .
不需要额外的注册,这也是行不通的,因为处理程序已经注册为可以在这里看到的开放式泛型。 The
ServiceFactory
registration takes care of creating those handlers. ServiceFactory
注册负责创建这些处理程序。
FYI: I created a nuget-package for registering MediatR
with Autofac
that even can be used together with default-service-provider . 仅供参考:我创建了一个nuget-package,用于向
Autofac
注册MediatR
,甚至可以与默认服务提供商一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.