Reputation: 8480
I have an enum CommandType
with all possible commands. And I have a lot of classes having the same base class Command
.
Then I can configure specific objects using the code like this:
<object type="Example.Command.MoveCommand">
<property name="StepSize" value="10" />
</object>
Now I would like to create Command
instances (each time a new one; not singleton) by CommandType
value. How to configure such a mapping using Spring.NET?
Upvotes: 0
Views: 1226
Reputation: 10557
I think you are looking for ServiceLocator functionality, which I don't think you can achieve with spring.net by only changing the configuration. Note that the ServiceLocator
pattern is generally discouraged from a dependency-injection point of view, because it makes your object aware of its di container.
If you do need a ServiceLocator
and don't mind tying your object to the Spring DI container, following could be a solution.
I assume your current code is something like this:
public class CommandManager
{
Dictionary<CommandType, Command> { get; set; } // set using DI
public Command GetBy(CommandType cmdKey)
{
return Dictionary[cmdKey];
}
}
Map the enum values to names of objects in you spring config by replacing your current Dictionary<CommandType, Command>
with a Dictionary<CommandType, string>
. Then use the current spring context to get the desired object:
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);
}
}
Don't forget to set the scope of your command objects to prototype
:
<object name="moveCommand"
type="Example.Command.MoveCommand, CommandLib"
scope="prototype">
<property name="StepSize" value="10" />
</object>
Now every time CommandManager.GetBy(myKey)
is called, a new instance is created.
Upvotes: 1