2

當我試圖找出如何讓使用Activator.CreateInstance創建的對象溫莎城堡解決依賴關係注入實例。解決使用Activator.CreateInstance

目前,當我創建對象這樣,創建的對象內部的依賴關係沒有得到解決。我搜查了一下,看看是否有一種溫莎方法可以做同樣的事情,同時也解決了依賴問題,但是到目前爲止我還沒有發現任何東西。

至於我爲什麼要創建這樣,我打約一個基本的文字遊戲,一點樂趣實例,這些實例都是基於用戶輸入的命令被創建,所以我需要創建基於實例在一個字符串上(當前命令被映射到一個字典中,然後使用上面的方法創建一個類型)。

感謝您的幫助。

+0

你爲什麼不解決,而不是首先使用Activator.CreateInstance與溫莎對象的地方之一? – 2011-02-07 04:50:20

+0

我現在在做。請參閱下面的答案以瞭解我當前的實際情況。 – 2011-02-07 04:51:12

回答

2

AFAIK您可以在castle windsor註冊,您可以註冊所謂的「命名實例」,因此您可以通過解決容器中的問題來創建需要的對象,而無需處理Activator.CreateInstance,肯定無法執行IoC。 基本上你有一個鍵登錄您的組件:

AddComponent(String key, Type classType) 

,然後調用

Resolve(string Key) 

有回來resoved所有依賴正確創建您的組件。

+0

謝謝Felice,你的回答非常有幫助!我將在下面發佈我的最終解決方案作爲另一個答案,並將您的答案設置爲接受的答案。歡呼的幫助和微調正確的方向。 – 2011-02-06 22:11:02

2

要在菲菲給出的答案擴大我覺得這一定是有用的張貼我來到了基於公認的答案的解決方案。

目前我的命令均通過一個IDictionary<TKey,TValue>映射但很快就會移動到另一個介質(XML,JSON等)。

這裏是我如何註冊compnents用戶輸入命令:

public void InstallUserCommands(IWindsorContainer container) 
{ 

    var commandToClassMappings = new Dictionary<string, string> 
          { 
           {"move", "MoveCommand"}, 
           {"locate","LocateSelfCommand"}, 
           {"lookaround","LookAroundCommand"}, 
           {"bag","LookInBagCommand"} 
          }; 

    foreach (var command in commandToClassMappings) 
    { 
    var commandType = Type.GetType("TheGrid.Commands.UserInputCommands." + command.Value); 
    container.Register(Component.For(commandType).Named(command.Key)); 

    } 
} 

,並解決實例:

public UserCommandInputMapperResponse Invoke(UserCommandInputMapperRequest request) 
{ 
    var container = new WindsorContainer(); 
    container.Install(FromAssembly.This()); 

    IUserInputCommand instance; 

    try 
    { 
    instance = container.Resolve<IUserInputCommand>(request.CommandName.ToLower().Trim()); 
    } 
    catch (Exception) 
    { 
    instance = null; 
    } 

    return new UserCommandInputMapperResponse 
       { 
        CommandInstance = instance 
       }; 
} 
1

一個更好的實施,溫莎明智的,將是利用打字的工廠。使用類型化工廠,您的代碼不必引用容器,因爲工廠實現將自動爲您創建。

使用類型化的工廠,你的工廠看起來是這樣的:

public interface IUserInputCommandFactory 
{ 
    IUserInputCommand GetMove(); 
    IUserInputCommand GetLocate(); 
    IUserInputCommand GetLookAround(); 
    IUserInputCommand GetBag(); 
} 

和溫莎將每個工廠方法轉發到相應的解決 - 例如GetMove將變爲container.Resolve<IUserInputCommand>("Move")

更多信息請參見typed factory docs ("'get' methods lookup by name)

我覺得這是在溫莎真正的亮點:)