2016-05-30 65 views
0

我有通用接口的簡單refistatiion統一DI。泛型類型註冊和IsRegistered方法

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

它容易使解決上unityContainer.Resolve<IMyInterface<MyGenericType>>MyClass<MyGenericType>和它的作品。

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

的問題是:1。 爲什麼? 2.如何檢查unityContainer.Resolve<IMyInterface<MyGenericType>>是否可能?

回答

0

這是我的調查結果。

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