我认为您正在寻找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, Command> 替换为Dictionary<CommandType, string>,将枚举值映射到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),都会创建一个新实例。