2013-04-20 49 views
2

我已经看到了Membus的IoC的功能,我试图来装到简单的注射器Membus和简单喷油器 - 接线命令处理程序自动接口

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>(); 
} 

当然从membus的IEnumerable<object> IocAdapter.GetAllInstances(Type desiredType)接口期望集合,使得多个处理程序可以调用。

用SimpleInjector IoC与Membus结婚的最佳方式是什么?

脚注

我看到其他的方式通过公约wireup menbus:

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容器坚持处理寿命范围,并避免实例命令处理程序并在需要之前手动连线它们。

回答

2

您可以有多个注册。下面是一个例子(道歉,但我的电脑今天去世了,我在记事本写这):

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>>(); 
} 

你会发现这些版本的RegisterManyForOpenGeneric的和GetAllInstances方法描述here

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

+0

请注意,虽然这些实现的注册集合中的顺序是不确定的。如果顺序很重要,则将已排序的列表传递给RegisterAll方法。例如:'implTypes.OrderBy(t => t.Name)'。 – Steven 2013-04-21 07:34:29

1

至于其他信息,this blog post here(免责声明 - 我的网站)概述了如何MemBus这些天连接到DI容器。

+0

感谢创建membus标签,我没有足够的法力创造:)这使我对约'SetHandlerInterface'第二个相关的问题在这里http://stackoverflow.com/questions/16125285/multiple-types-for-sethandlerinterface -with-membus和 - IOC-容器 – g18c 2013-04-20 21:17:48

相关问题