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?
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
ServiceLocatorpattern 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
ServiceLocatorand 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:
Map the enum values to names of objects in you spring config by replacing your current
Dictionary<CommandType, Command>with aDictionary<CommandType, string>. Then use the current spring context to get the desired object:Don't forget to set the scope of your command objects to
prototype:Now every time
CommandManager.GetBy(myKey)is called, a new instance is created.