I have a WPF app running, which needs all operations that affect the UI to be on the UI Thread. WPF also provides a Dispatcher class that handles this - so I extracted that into a dependency.
public interface UIActionExecutor
{
void Do(Action action);
}
So in my production code, I use an exported implementation which delegates to the WPF Dispatcher. I'm using MEF for DI.
Now the problem, in my acceptance tests, I need to replace the part / object in the container that responds to UIActionExecutor
by a Mock. So I need to remove ExecutorUsingWpfDispatcher
from my container and add MockUIActionExecutor
in its place. This sounds pretty simple (if I was not using MEF)... but my searching skills haven't helped me find an answer as to how to do this with the MEF container ?
Update: If anyone wants to know why/how the solution works - read Glenn Block's blog post#2. This is what I ended up using
var defaultExportProvider = new CatalogExportProvider(__defaultCatalog);
var catalogOfMocks = new AssemblyCatalog(assemblyExportingMocks);
// order of params important (precedence left to right)
__container = new CompositionContainer(catalogOfMocks, defaultExportProvider);
defaultExportProvider.SourceProvider = __container
GetExportedValue<IRole>
now returns the mock. However creating an object that imports IRole still uses the Real implementation. e.g.testContainer.GetExportedValue<ConsumingObject>
still uses the real implementation. – Whispering