Unity DI。通用类型注册和IsRegistered方法

时间:2016-05-30 17:53:30

标签: c# generics unity-container

我对通用接口的简单修改

unityContainer.RegisterType(typeof(IMyInterface<>), typeof(MyClass<>));

很容易在MyClass<MyGenericType>上解析unityContainer.Resolve<IMyInterface<MyGenericType>>并且有效。

unityContainer.IsRegistered<IMyInterface<MyGenericType>>()False

问题是: 1.为什么? 2.如何检查unityContainer.Resolve<IMyInterface<MyGenericType>>是否可能?

1 个答案:

答案 0 :(得分:3)

这是我的调查结果。

public static class UnityExtenstions
{
    public static bool IsRegisteredAdvanced<T>(this IUnityContainer unityContainer)
    {
        return IsRegisteredAdvanced(unityContainer, typeof(T));
    }

    public static bool IsRegisteredAdvanced(this IUnityContainer unityContainer, Type type)
    {
        var result = unityContainer.IsRegistered(type);
        if (result == false)
        {
            var genericTypeDefinition = GetGenericTypeDefinition(type);
            if (genericTypeDefinition != null)
            {
                result = unityContainer.IsRegistered(genericTypeDefinition);
            }
        }
        return result;
    }

    private static Type GetGenericTypeDefinition(Type type)
    {
        if (type == null) return null;
        var typeInfo = type.GetTypeInfo();
        return (typeInfo.IsGenericType == true)
            && (typeInfo.IsGenericTypeDefinition == false)
             ? type.GetGenericTypeDefinition()
             : null;
    }
}
相关问题