2

以下のコードがあり、ジェネリックの異なるバリアントごとにシングルトンを登録したいと考えています。これは可能ですか?現在、同じオブジェクト タイプではないため、アサーションは失敗します。

public interface IGenericClass<T>
{
    string GetToString();
}

public class GenericClass<T> : IGenericClass<T>
{
    public string GetToString()
    {
        return typeof (T).FullName;
    }
}

[Test]
public void test()
{
    var container = new Container();

    container.RegisterOpenGeneric(
        typeof(IGenericClass<>), 
        typeof(GenericClass<>));

    var instance1 = container.GetInstance<IGenericClass<double>>();
    var instance2 = container.GetInstance<IGenericClass<double>>();

    //this should assert true
    Assert.IsTrue(object.ReferenceEquals(instance1, instance2));
}
4

1 に答える 1

2

使用するだけRegisterSingleOpenGenericです:

_container.RegisterSingleOpenGeneric(
    typeof(IGenericClass<>), 
    typeof(GenericClass<>));
于 2013-01-31T14:56:28.950 に答える