2011-03-02 56 views
0

我有一個enum CommandType包含所有可能的命令。而且我有很多具有相同基類Command的類。Spring.NET:枚舉到對象映射

然後我就可以使用這樣的代碼配置特定對象:

<object type="Example.Command.MoveCommand"> 
    <property name="StepSize" value="10" /> 
</object> 

現在我想創建Command實例(每次一個新的,不單身)由CommandType值。如何使用Spring.NET配置這樣的映射?

+0

你是什麼意思「創建實例的命令類型值」?你的意思是在你的代碼中? – Marijn 2011-03-03 06:23:04

+0

現在我在Spring中創建一個映射,初始化Dictionary 。當然,在這種情況下,我有單身命令對象。 – alexey 2011-03-04 11:22:46

回答

1

我想你正在尋找ServiceLocator的功能,我認爲你不能通過改變配置來實現spring.net。請注意,ServiceLocator模式通常不受依賴注入的影響,因爲它使對象知道它的di容器。

如果您確實需要ServiceLocator並且不介意將您的物體綁定到Spring DI容器上,下面的可能是的一個解決方案。

我假設你當前的代碼是這樣的:

public class CommandManager 
{ 
    Dictionary<CommandType, Command> { get; set; } // set using DI 

    public Command GetBy(CommandType cmdKey) 
    { 
    return Dictionary[cmdKey]; 
    } 
} 

在您在與Dictionary<CommandType, string>替換當前的Dictionary<CommandType, Command> Spring配置地圖枚舉值對象的名稱。然後使用當前Spring上下文來獲取所需的對象:

using Spring.Context; 
using Spring.Context.Support; 

public class CommandManager 
{ 
    Dictionary<CommandType, string> { get; set; } // set using DI; values are object names 

    public Command GetBy(CommandType cmdKey) 
    { 
    string objName = Dictionary[cmdKey]; 
    IApplicationContext ctx = ContextRegistry.GetContext(); 

    return (Command)ctx.GetObject(objName); 
    } 
} 

不要忘記你的命令對象的範圍設置爲prototype

<object name="moveCommand" 
     type="Example.Command.MoveCommand, CommandLib" 
     scope="prototype"> 
    <property name="StepSize" value="10" /> 
</object> 

現在每次CommandManager.GetBy(myKey)被調用時,一個新的實例已創建。