我对通用接口的简单修改
unityContainer.RegisterType(typeof(IMyInterface<>), typeof(MyClass<>));
很容易在MyClass<MyGenericType>
上解析unityContainer.Resolve<IMyInterface<MyGenericType>>
并且有效。
但unityContainer.IsRegistered<IMyInterface<MyGenericType>>()
为False
问题是:
1.为什么?
2.如何检查unityContainer.Resolve<IMyInterface<MyGenericType>>
是否可能?
答案 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;
}
}