Question

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?

Was it helpful?

Solution 2

You can query the container model like:

var policyNames =  Container.Model.AllInstances.Where(x => x.PluginType == typeof(IPolicy)).Select(x => x.Name);

HTH

OTHER TIPS

The answer of @ozczecho is what you are looking for.

Every Instance in StructureMap has a name, even the ones you don't explicitly name. If no name is specified, StructureMap uses a Guid string to identify the Instance.

If you want to filter out the instances with Guid strings change it to the following code:

Predicate<string> isGuid = s =>
{
    Guid g;

    return Guid.TryParse(s, out g);
};

var names = _container.Model.AllInstances.Where(x => x.PluginType == typeof (IPolicy))
                                        .Where(x => !isGuid(x.Name))
                                        .Select(x => x.Name)
                                        ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top