I'm just starting with Unity IOC, hoping someone will help. I need to be able to switch the dependencies in Unity at run time. I have two containers each for production and dev/test environments, "prodRepository" and "testRepository" defined in the web.config as follows:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="TestDataService" type="MyApp.API.Data.TestDataRepository.TestDataService, MyApp.API.Data" />
<alias alias="ProdDataService" type="MyApp.API.Data.ProdDataRepository.ProdDataService, MyApp.API.Data" />
<assembly name="MyApp.API.Data" />
<container name="testRepository">
<register type="MyApp.API.Data.IDataService" mapTo="TestDataService">
<lifetime type="hierarchical" />
</register>
</container>
<container name="prodRepository">
<register type="MyApp.API.Data.IDataService" mapTo="ProdDataService">
<lifetime type="hierarchical" />
</register>
</container>
</unity>
In the WebApiConfig class the Unit is configured as follows
public static void Register(HttpConfiguration config)
{
config.DependencyResolver = RegisterUnity("prodRepository");
//... api configuration ommitted for illustration
}
public static IDependencyResolver RegisterUnity(string containerName)
{
var container = new UnityContainer();
container.LoadConfiguration(containerName);
return new UnityResolver(container);
}
Just for test I created a simple controller and action to switch the configuration:
[HttpGet]
public IHttpActionResult SwitchResolver(string rName)
{
GlobalConfiguration.Configuration
.DependencyResolver = WebApiConfig.RegisterUnity(rName);
return Ok();
}
and I call it from a web browser: http://localhost/MyApp/api/Test/SwitchResolver?rName=prodRepository
When I try to retrieve the actual data from the repositories via the API, at first it comes from "prodRepository", understandably, as that's how it is initialized in the code. After I switch it to "testRepository" from the browser, the data comes from the test repo as expected. When I switch it back to prodRepository, the API keeps sending me the data from the test repo. I see in the controller that the GlobalConfiguration.Configuration .DependencyResolver changes the container and registrations to the ones specified in the URL query as expected, but it seems to change the configuration only once then stays at that configuration.
Ok, so this evil plan is what I came up with but as I am new to this I am probably going wrong direction altogether. I need to be able to specify dynamically at run-time which container to use, hopefully without reloading the API. Does the above code make sense or what would you suggest?