In my application I have the IPolicy
interface and a number of concrete implementations. Let's say BasicPolicy
and AdvancedPolicy
. I configure the StructureMap container by adding named instances like so:
class MyRegistry : Registry
{
public MyRegistry()
{
For<IPolicy>().Use<BasicPolicy>().Named("Basic policy");
For<IPolicy>().Use<AdvancedPolicy().Named("Advanced policy");
}
}
I also have a factory to retrieve policies by name:
class PolicyFactory : IPolicyFactory
{
private readonly IContainer _container;
public PolicyFactory(IContainer continer)
{
_container = container;
}
public IPolicy GetPolicy(string name)
{
return _container.GetInstance<IPolicy>(name);
}
}
Now what I would like to have in the factory is a method that returns a list of all the names. So that when I call var names = _factory.GetPolicyNames()
the names
variable will hold { "Basic policy", "Advanced policy" }
.
Having this I can pass the list on to the presentation layer to display it in a combobox where the user can choose which policy to apply. Then, the chain of calls will lead back to _factory.GetPolicy(name);
I failed to find it in StructureMap. If it's possible, how would you do it? If not, what is the best workaround?
You can query the container model like:
var policyNames = Container.Model.AllInstances.Where(x => x.PluginType == typeof(IPolicy)).Select(x => x.Name);
HTH