1
votes

I am looking at structuremap as an IOC/DI tool. Looking at this example:

http://docs.structuremap.net/QuickStart.htm

The only thing that does not make sense is, if I have an interface and derive several concrete types from it, in the code:

public class ClassThatGetsAnIValidator { public void SaveObject(object objectToSave) { // Go get the proper IValidator from StructureMap IValidator validator = ObjectFactory.GetInstance();

        var notification = validator.Validate(objectToSave);
        if (notification.IsValid())
        {
            // save the object
        }
    }
}

How do I know which validator I get? IE I may have an AlphaBetValidator, NumericValidator, etc, with different method bodys and so on.....

I think this is the point:

Registering "what" and "how" StructureMap should build or find those requested services (the tedious part, but it's gotten much better over the years)

Which I struggle to grasp.

Please help.

Thanks

1

1 Answers

1
votes

From the documentation:

If there is only one Instance for a registered PluginType, that Instance will be assumed to be the default for the PluginType. Otherwise, if there is more than one Instance for a PluginType, StructureMap must be explicitly told which Instance is the default, otherwise the call to GetInstance() will throw an exception (202).

To resolve to a particular instance you could use the naming mechanism. From the same documentation page:

Sometimes it's advantageous to retrieve a "named" instance of a type. Let's say that you're building a system that needs to connect to interface with multiple external shipping systems. You've designed an interface for your system called IShippingSystem that hides the details of each external shipping behind adapters. The rest of your code should only "know" how to interact with the IShippingSystem, but at some point, some class needs to know how to select and retrieve the proper instance of IShippingSystem. Before the advent of IoC containers like StructureMap, you would have coded a Factory class and possibly a Builder class by hand to do the construction. With StructureMap, this code is simply a call to the ObjectFactory.GetNamedInstance(Type, string) method.

IShippingService internationalService = ObjectFactory.GetNamedInstance<IShippingService>("International");

IShippingService domesticService = ObjectFactory.GetNamedInstance<IShippingService>("Domestic");