2

Ninjectを使用して、あるメソッドを別の実装に再バインドしたいのですが、それは可能ですか?

私は詳しく説明します、私は2つの異なる実装でこのインターフェースを持っています:

public interface IPersonFacade
{
  List<string> GetPeople();
  string GetName();
}

public class PersonFacade:IPersonFacade
{
  //Implement Interface fetching data from a db.
}

public class PersonFacadeStub:IPersonFacade
{
  //Implement Interface with some static data
}

Ninject mvc拡張機能を使用していて、NinjectModule実装があります。

public class ServiceModule:NinjectModule
{   
  public override void Load()
  {
    Bind<IPersonFacade>().To<PersonFacade>();
  }
}

質問に戻りますが、GetPeople()メソッドを再バインドして、PersonFacadeStubの実装を使用することはできますが、IPersonFacadeはPersonFacadeのGetNameを引き続き使用しますか?

4

1 に答える 1

2

それは不可能だと思います。NInjectは、他のDIコンテナと同様に、メソッドではなくタイプを管理します。同じインターフェイスパターンのさまざまなメソッドにさまざまなタイプを使用する場合は、Compositeが役立つ場合があります。

public class CompositePersonFacade : IPersonFacade
{
    private readonly IPersonFacade realFacade;
    private readonly IPersonFacade stubFacade;

    public CompositePersonFacade(IPersonFacade realFacade, IPersonFacade stubFacade)
    {
        this.realFacade = realFacade;
        this.stubFacade = stubFacade;
    }

    public List<string> GetPeople()
    {
        return stubFacade.GetPeople();
    }

    public string GetName()
    {
        return realFacade.GetName();
    }
}

また、バインディングを変更します。

Bind<IPersonFacade>().To<CompositePersonFacade>()
    .WithConstructorArgument("realFacade", 
                  context => context.Kernel.Get<PersonFacade>())
    .WithConstructorArgument("stubFacade", 
                  context => context.Kernel.Get<PersonFacadeStub>());
于 2012-04-04T15:04:57.490 に答える