2

私は次のテストケースを取得しましたが、次の場合に失敗します。

期待されるもの:ArxScriptsTests.Engines.Ioc.Examples + Aと同じですが、そうでした:ArxScriptsTests.Engines.Ioc.Examples + A

問題は、それを正しくする方法ですか?

[TestFixture]
public class Examples
{
    public interface IInterface
    {

    }

    public abstract class BaseClass : IInterface
    {

    }

    public class A : BaseClass
    {

    }

    public class B : BaseClass
    {

    }


    [Test]
    public void TestMethod1()
    {
        IKernel kernel = new StandardKernel();

        // Bind to self
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<BaseClass>()
            .BindToSelf()
            .Configure(b => b.InSingletonScope())
            );

        // Bind to IInterface
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<IInterface>()
            .BindSelection((type, baseTypes) => new List<Type> { typeof(IInterface) })
            .Configure(b => b.InSingletonScope())
            );


        // Bind to BaseClass
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<BaseClass>()
            .BindSelection((type, baseTypes) => new List<Type> { typeof(BaseClass) })
            .Configure(b => b.InSingletonScope())
            );




        List<IInterface> byInterface = new List<IInterface>(kernel.GetAll<IInterface>());
        List<BaseClass> byBaseClass = new List<BaseClass>(kernel.GetAll<BaseClass>());


        Assert.AreSame(byInterface[0], byBaseClass[0]);
    }
}

1つの解決策は

[Test]
public void TestMethod1()
{
    IKernel kernel = new StandardKernel();

    // Bind to Both
    kernel.Bind(x => x
        .FromThisAssembly()
        .SelectAllClasses().InheritedFrom<IInterface>()
        .BindSelection((type, baseTypes) => new List<Type> { typeof(IInterface), typeof(BaseClass) })
        .Configure(b => b.InSingletonScope())
        );


    List<IInterface> byInterface = new List<IInterface>(kernel.GetAll<IInterface>());
    List<BaseClass> byBaseClass = new List<BaseClass>(kernel.GetAll<BaseClass>());


    Assert.AreSame(byInterface[0], byBaseClass[0]);
}

しかし、両方のバインディングを異なるモジュールに配置しようとすると、それは役に立ちません。それとも、それはとにかく悪い考えですか?

4

1 に答える 1

1

バインディングにはスコープが定義されています。2 つのバインディングがスコープを共有することはできません。

あなたがすべきこと:

  1. の代わりにインターフェイスを使用します。BaseClass
  2. どのタイプのカルセがシングルトンであるかを定義するコーディング規則を定義します。例: Service で終わるような特別な命名
  3. BindAllInterfaces を使用してバインドする

規則を使用する場合、これは消費者の観点からではなく、サービス プロバイダーの観点から行う必要があります。したがって、さまざまなモジュールでさまざまなインターフェイス タイプのバインディングを用意する必要はありません。

于 2013-02-20T12:01:08.860 に答える