I recently wrote this in an email to my co-workers. This makes it a bit out of context here...but hopefully it will make sense!
I had to refresh my mind a little bit to figure out how to programatically swap out instance momentos in StructureMap...so I figured I would send this out to you all too.
In case you were wondering why we are using StructureMap for newing up objects rather than just instantiating them directly (other than good design with decoupling :) )... up to this point I have not been able to produce any good reasons in this project for being able to swap out objects but just came across an instance. I am currently working on porting our caching via .net httpcontext to caching with memcached (distributed server cloud).
As a result of this we now have two objects that perform the same tasks...but with different implementation. One that uses the cache facility with .net's HttpContext and one that uses the MemCached implementation. The interface for both of these objects is the same. The interface is called ICache.
We have a Cache object that inherits from ICache. We also have a MemcachedCache object that inherits from the same ICache. We then have pluggable attributes defined for both caching classes [Pluggable("Cache")] and [Pluggable("MemCached")]. The plugin family for ICache is [PluginFamily("MemCached")]. This means that the default object to be returned by StructureMap is the MemcachedCache class as the default value for the interface's PluginFamily attribute matches the Pluggable attribute of the MemcachedCache object.
However, in our tests (and possibly while performing local dev work), we would want to use the HttpContext cache to remove dependencies as much as possible and to speed along the tests. That being said we would also want the ability to test our MemCache installations from time to time too!
This can be done with the same set of unit tests with the InjectStub method that the StructureMap.ObjectFactory presents us with.
ICache cache1 = ObjectFactory.GetInstance<ICache>(); //MemcachedCache caching
ObjectFactory.InjectStub(typeof (ICache), new Cache());
ICache cache2 = ObjectFactory.GetInstance<ICache>(); //HttpContext caching
ICache cache3 = ObjectFactory.GetInstance<ICache>(); //back to the MemcachedCache caching
Setting the default class can also be done in the StructureMap.Config file:
<?xml version="1.0" encoding="utf-8" ?>
<Assembly Name="[assembly name]" />
DefaultKey="[MemCached or Cache]" />
Let me know if there are any questions!