我有以下代码,并希望为泛型的每个不同变体注册一个单例。这可能吗?当前,断言失败,因为的对象类型不同。

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));
}

最佳答案

只需使用RegisterSingleOpenGeneric

_container.RegisterSingleOpenGeneric(
    typeof(IGenericClass<>),
    typeof(GenericClass<>));

关于c# - 使用Simple Injector注册开放的通用单例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14628013/

10-12 16:28