1 Loading Configuration File Information into a Container
Eugene Sadovoi редактировал(а) эту страницу 2019-01-23 20:40:14 -05:00

Adding a Unity configuration section to a configuration file neither create an actual container nor configures it. You must create a Unity container instance, add Unity.Configuration extension to the container, read the configuration file, and load the configuration file information into the container.

To load the configuration file information into a container, use the LoadConfiguration extension method on IUnityContainer. This interprets the default configuration file for your application, seeks the Unity configuration section, and configures the container. The LoadConfiguration extension method has several overloads. Unity offers a convention-based approach to configuring your container that can be applied in most cases. To take advantage of this you must use the default Unity configuration section name of unity and specify an un-named container in your App.config or Web.config file. The following example uses this approach.

IUnityContainer container = new UnityContainer().LoadConfiguration();

The configuration for a named container can be loaded from the default configuration section by providing the name of the container to the LoadConfiguration method as shown in the following example:

IUnityContainer container = new UnityContainer().LoadConfiguration("otherContainerElement");

If your configuration is in a different section (either with a different name or from a different file entirely), you must first load the section object through ConfigurationManager and then pass the section to the LoadConfiguration method, as shown in the following example:

IUnityContainer container = new UnityContainer()
    .LoadConfiguration(section)  // Loads unnamed <container> element
    .LoadConfiguration(section, "otherContainerElement"); // named <container> element

You can also load multiple configurations into the same container. Non-conflicting configurations will simply be added, and if there is a conflict, such as two mappings for the same type, then the last configuration added will be the one that is used. The previous example illustrates the additive feature for configuration. There is also an API on the UnityConfigurationSection object that can be used to configure a container. Once you have obtained the section object of the ConfigurationManager, you can call its Configure method to apply configuration to a container:

var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
IUnityContainer container = new UnityContainer();
section.Configure(container); // Unnamed <container> element
section.Configure(container, "otherContainerElement"); // named container element

In general, the LoadConfiguration extension method is preferred as it is easier to read and use.