2017-08-03 110 views
-1

怎麼樣,我有幾個類實現了ICommanHandler接口多次,因爲我可以使用Unity自動註冊它們,而不是一個一個地註冊它們。謝謝。Unity自動註冊ICommandHandler

public class CarCommandHandler:ICommandHandler<CreateCar> 
           ICommandHandler<DeleteCar> 
{ 
    ...... 
} 


public class EngineCommandHandler:ICommandHandler<CreateEngine> 
            ICommandHandler<DeleteEngine> 
{ 
    ...... 
} 



public static void RegisterTypes(IUnityContainer container) 
{ 
    container.RegisterType<ICommandHandler<CreateCar>, CarCommandHandler>(); 

    container.RegisterType<ICommandHandler<DeleteCar>, CarCommandHandler>(); 

    container.RegisterType<ICommandHandler<CreateEngine>, EngineCommandHandler>(); 

    container.RegisterType<ICommandHandler<DeleteEngine>, EngineCommandHandler>(); 
} 
+0

你嘗試'container.RegisterType(typeof運算(ICommandHandler <>) ,CarCommandHandler,「firstRegistration」); container.RegisterType(typeof(ICommandHandler <>),EngineCommandHandler,「secondRegistration」);'? –

+0

RegisterType接受的參數不匹配:0 –

+0

是的,小錯誤,檢查它:'你試過container.RegisterType(typeof(ICommandHandler <>),typeof(CarCommandHandler),「firstRegistration」); container.RegisterType(typeof(ICommandHandler <>),typeof(EngineCommandHandler),「secondRegistration」);' –

回答

0

您需要遍歷所有實現ICommandHandler<>的類型並註冊它們。代碼如下可以這樣做:

public static void RegisterAllImplementations(this UnityContainer container, Type openInterfaceType) 
    { 
     int registerCount = 0; 
     // Iterate all types from current assembly 
     foreach (var typeItem in Assembly.GetExecutingAssembly().GetTypes()) 
     { 
      foreach (var interaceItem in typeItem.GetInterfaces()) 
      { 
       if (interaceItem.IsGenericType && interaceItem.GetGenericTypeDefinition() == openInterfaceType) 
       { 
        container.RegisterType(interaceItem, typeItem, $"{registerCount++}"); 
       } 
      } 
     } 
    } 

的調用:

var container = new UnityContainer(); 
    container.RegisterAllImplementations(typeof(ICommandHandler<>)); 

讓我知道,如果事情不工作

+0

它的作品完美,非常感謝你! –