In my StructureMap bootstrapping code I'm using a custom convention to scan assemblies and add interface/implementation pairs to the object graph as named instances. Essentially I have some logic which checks configuration settings and drills down to this statement depending on various conditions:
registry.For(interfaceType).Use(type)
.Named(implementationName);
This adds all of the named instances well enough. However, I'd also like to add a default instance in the event that an instance name is not specified. However, the default instance isn't always the last one added to the graph. Sometimes other named instances are added afterward during the scanning. It would seem, though, that whichever instance is added last, regardless of whether or not it's named, is always the default.
I've tried various combinations of the fluent API, including:
registry.For(interfaceType).Add(type);
or:
registry.For(interfaceType).Use(type);
Even some of the ones marked as deprecated. But the resulting behavior is always that the last one is the default. So if the order of adding implementations is something like this:
The resulting behavior is that the "Mock" implementation is used as the default when no name is specified. Debugging into AllInstances
in the container, I see in the following order:
Debugging into a logging statement when called from the container without an instance name, however, results in the Mock implementation being used.
Is there a way to add a default instance to the object graph while still being able to add named instances afterward?
The Add
method will add instances (if you need to add named instances or add multiple instances for to use with collections/enumerations). If no explicit default is registered (using the Use
method), the last instance added will become the default instance. The Use
method is intended for setting the default instance. If you invoke Use
multiple times, the last instance registered will become default.
In order to set a default instance and then register further named instances you should be able to do it like this:
registry.For(typeof(Logger)).Use(typeof(Log4Net)).Named("Log4Net");
registry.For(typeof(Logger)).Add(typeof(Mock)).Named("Mock");
This will make the Log4Net
instance the default and also accessible as a named instance. The Mock
instance will be available as a named instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With