【问题标题】:Spring.NET: Enum to object mappingSpring.NET:枚举到对象的映射
【发布时间】:2011-03-02 18:06:33
【问题描述】:

我有一个枚举 CommandType,其中包含所有可能的命令。而且我有很多类具有相同的基类Command

然后我可以使用如下代码配置特定对象:

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

现在我想通过CommandType 值创建Command 实例(每次都是一个新实例;不是单例)。如何使用 Spring.NET 配置这样的映射?

【问题讨论】:

  • “通过命令类型值创建实例”是什么意思?你的意思是在你的代码中?
  • 现在我在 Spring 中创建了这个映射,初始化了一个 Dictionary。当然,在这种情况下,我有单例 Command 对象。

标签: c# .net dependency-injection ioc-container spring.net


【解决方案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&lt;CommandType, Command&gt; 替换为Dictionary&lt;CommandType, string&gt;,将枚举值映射到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),都会创建一个新实例。

【讨论】:

    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多