Reputation: 53
I am trying to merge my unity files into a single file separated by child containers in order to simplify the end system configuration but am having difficulty getting it figured out. So far I have implemented my own WcfServiceFactory and have overrode the ConfigureContainer to load up our Unity but am unable to find a way to load up the child container. Here is what I have so far:
public class WcfServiceFactory : UnityServiceHostFactory
{
/// <summary>
/// Configures the container.
/// </summary>
/// <param name="container">The container.</param>
protected override void ConfigureContainer(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
container.LoadConfiguration();
container.AddExtension(new ConfigExtension());
var childContainer = container.CreateChildContainer();
childContainer.LoadConfiguration(ConfigurationManager.AppSettings["ChildUnityContainer"]);
}
}
Please let me know if you have a way of doing this.
Upvotes: 0
Views: 1110
Reputation: 22655
Unity configuration is additive so I'm not sure you need child containers here at all. Based on what I see in the posting it should be possible to "build up" one container with all the configuration you need. [If this assumption is incorrect it would help to explain why and the issues that you are hitting.]
Child containers are usually used when you want to keep the original container and use most of it's settings but with some configuration differences (e.g. singleton lifetimes are not really global singletons but scoped to the child container).
Based on the above I think you should be able to configure one container with each ConfigureContainer()
overwriting the particular configuration in the previous configuration:
protected override void ConfigureContainer(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
// Load default container
container.LoadConfiguration();
container.AddExtension(new ConfigExtension());
// Load child configuration on top of first configuration
container.LoadConfiguration(ConfigurationManager.AppSettings["ChildUnityContainer"]);
}
After this runs the default configuration and the child container should be loaded. For example if the configuration looked like this:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="IDoctor" mapTo="Doctor" />
<register type="IDoctor" mapTo="EyeDoctor" name="eye"/>
</container>
<container name="Child">
<register type="IDoctor" mapTo="EyeDoctor"/>
</container>
</unity>
After the calls LoadConfiguration()
and LoadConfiguration("Child")
the container would have 2 registrations: IDoctor
mapped to EyeDoctor
(this overrides the first registration in the default container) and IDoctor
with name "eye" mapped to EyeDoctor
(existing registration is kept after second LoadConfiguration
call).
Upvotes: 2