2

Simple Injector に接続しようとした Membus の IoC 機能を見てきました

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 からのインターフェースはコレクションを想定しているため、複数のハンドラーを呼び出すことができます。

Membus を SimpleInjector IC と組み合わせる最善の方法は何でしょうか?

脚注

私は、慣習によってメンバスを接続する他の方法を見てきました:

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 コンテナーを使用してライフタイム スコープを処理し、コマンド ハンドラーをインスタンス化して必要になる前に手動で接続することを避けたいと考えています。

4

1 に答える 1

2

複数登録できます。以下に例を示します (申し訳ありませんが、私の PC は今日死んでしまい、これをメモ帳に書いています):

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メソッドのこれらのバージョンを見つけることができます

この手法を使用して、パブリッシュ/サブスクライブ フレームワークをサポートします。独立したをn 個持つことができます CommandHandler

于 2013-04-20T20:13:21.630 に答える