简体   繁体   English

在Mediatr命令处理程序中注入依赖项

[英]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 . 我可以使用builderapi项目的角度注入一些东西。

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 type CommandHandlers.ActivityCommandHandler can be invoked with the available services and parameters: Cannot resolve parameter System.String conStr of constructor Void .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM