6

Simple Injector IoC フレームワークを使用しています。実行時に依存関係の登録を変更できるようにしたいと考えています。たとえば、interface のAとの 2 つの実装があります。実装はアプリの起動時に登録されますが、実行時に変化する可能性のあるフラグに応じて、実装を切り替えたいと考えています。現在、すべてのコントローラーが継承するのイベントでこれを行っています。これが私がやろうとしていることのサンプルコードです。BIAOnActionExecutingBaseController

protected override void OnActionExecuting(
    ActionExecutingContext filterContext)
{
    if (IsRuntimeFlag)
    {
        // check current implementation type and 
        // change implementation to A
    }
    else
    {
        // check current implementation type and 
        // change implementation to B
    }

    base.OnActionExecuting(filterContext);
}

よろしくお願いします。

4

1 に答える 1

11

が構成値である場合IsRuntimeFlag(したがって、アプリケーションの存続期間中に変更することはできません)、次のように登録を行うことができます。

if (IsRuntimeFlag)
{
    container.Register<I, A>();
}
else
{
    container.Register<I, B>();
}

または同様に:

container.Register(typeof(I), IsRuntimeFlag ? typeof(A) : typeof(B));

アプリケーションの存続期間中に値が変更される可能性がある場合は、適切なインスタンスへのディスパッチを処理するプロキシまたはコンポジットが適切なソリューションです。

public sealed class RuntimeFlagIComposite : I
{
    private readonly A a;
    private readonly B b;

    public RuntimeFlagIComposite(A a, B b) {
        this.a = a;
        this.b = b;
    }

    void I.Method() => this.Instance.Method();

    private I Instance => IsRuntimeFlag ? this.a : this.b;
}

Aコンポジットはとに直接依存するため、B次のように簡単に登録できます。

container.Register<I, RuntimeFlagIComposite>();

// Register A and B with their required lifestyles
container.Register<A>(Lifestyle.Singleton);
container.Register<B>(Lifestyle.Transient);

コンポジットを具体的な実装Iではなく、抽象化自体に依存させることもできます。AB

public class RuntimeFlagIComposite : I
{
    private I a;
    private I b;

    public RuntimeFlagIComposite(I a, I b)
    {
        this.a = a;
        this.b = b;
    }
}

抽象化に応じて、Iこのクラスはより柔軟でテストしやすくなります。ただし、少し異なる方法で登録する必要があることを意味します。これは、 を使用して実行できますRegisterConditional。次に例を示します。

container.Register<I, RuntimeFlagIComposite>();

container.RegisterConditional<I, A>(c => c.Consumer.Target.Name == "a");
container.RegisterConditional<I, B>(c => c.Consumer.Target.Name == "b");
于 2012-08-23T05:56:43.137 に答える