I am currently using Unity with MOQ to do my unit testing for WCF. In the application’s code, I have the following:
private void MyMethod()
{
.....
.....
_proxy = new UnityContainer().LoadConfiguration().Resolve<IMyInterface>();
.....
}
In the application’s app.config, I have the following:
<container>
<register type="IMyInterface" mapTo="MyActualObject" />
</container>
In the unit test’s app.config, I replace that with my mock object implementation of the proxy.
<container>
<register type="IMyInterface" mapTo="MyMockObject" />
</container>
That is all working fine. But what I would like to do further is for certain tests, I would like to replace MyMockObject with a different mock object implementation.
Is it possible to change the registered type at runtime? I have tried modifying the application config during runtime but it fails to detect the change.
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section = (UnityConfigurationSection)appConfig.GetSection("unity");
section.Containers[0].Registrations[0].MapToName = "AnotherMockObject";
appConfig.Save();
Thanks!!
Yes its possible.
You can configure Unity as many times as you want. If there’s a conflict the most recent definition wins.
In your case if you want to make a runtime change, use the fluent API instead of the config file. Try something like this:
The documentation for Registering Types and Type Mappings