gpt4 book ai didi

c# - Membus 和 Simple Injector - 通过接口(interface)自动连接命令处理程序

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:16 24 4
gpt4 key购买 nike

我在 Membus 中看到了 IoC 功能,我试图连接到 Simple Injector

IEnumerable<object> IocAdapter.GetAllInstances(Type desiredType)
{
var found = SimpleInjectorContainer.GetAllInstances(desiredType);
return found;
}

我的想法是我将使用 RegisterManyForOpenGeneric(typeof<CommandHandler<>),typeof<CommandHandler<>).Assembly) 自动注册我的所有类型.

毫无疑问,通常有充分的理由,SimpleInjector 将不允许多次注册 - 但是,我想这样做是为了让不同的处理程序实现命令处理的不同方面/关注点。

public void MembusBootstrap()
{
this.Bus = BusSetup.StartWith<Conservative>()
.Apply <IoCSupport>(c =>
{
c.SetAdapter(SimpleInjectorWiring.Instance)
.SetHandlerInterface(typeof(HandleCommand<>));
})
.Construct();
}

public void SimpleInjectorBootstrap()
{
this.Container.Register<HandleCommand<AccountCreatedCommand>,
SetupNewAccountCommandHandler();

// next line will throw
this.Container.Register<HandleCommand<AccountCreatedCommand>,
LogNewAccountRequestToFile>();
}

当然是 IEnumerable<object> IocAdapter.GetAllInstances(Type desiredType)来自 membus 的接口(interface)需要一个集合,以便可以调用多个处理程序。

将 Membus 与 SimpleInjector IoC 结合的最佳方式是什么?

脚注

我见过按照惯例连接菜单总线的其他方法:

public interface YetAnotherHandler<in T> {
void Handle(T msg);
}

public class CustomerHandling : YetAnotherHandler<CustomerCreated>
...

var b = BusSetup
.StartWith<Conservative>()
.Apply<FlexibleSubscribeAdapter>(c => c.ByInterface(typeof(YetAnotherHandler<>))
.Construct();

var d = bus.Subscribe(new CustomerHandling());

但我真的很想坚持使用 IoC 容器来处理生命周期范围,并避免实例化命令处理程序并在需要它们之前手动连接它们。

最佳答案

您可以注册多个。这是一个示例(抱歉,我的电脑今天坏了,我正在用记事本写这个):

SimpleInjectorContainer.RegisterManyForOpenGeneric(typeof(CommandHandler<>),
AccessibilityOption.PublicTypesOnly,
(serviceType, implTypes) => container.RegisterAll(serviceType, implTypes),
AppDomain.CurrentDomain.GetAssemblies()
);

它们可以通过以下方式检索:

public IEnumerable<CommandHandler<T>> GetHandlers<T>()
where T : class
{
return SimpleInjectorContainer.GetAllInstances<CommandHandler<T>>();
}

您会发现这些版本的 RegisterManyForOpenGenericGetAllInstances 方法描述了 here

我使用这种技术来支持发布/订阅框架。您可以拥有 n独立 CommandHandler

关于c# - Membus 和 Simple Injector - 通过接口(interface)自动连接命令处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16123641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com