Share via


The Unity Configuration Schema

patterns & practices Developer Center

Download codeDownload PDFOrder Paperback

Unity 3 uses a the streamlined configuration schema introduced in Unity 2.0 for configuring Unity.

The following sections describe the schema configuration elements, their child elements, and their attributes in more detail:

  • The <unity> Configuration Section
  • The <container> Element
  • The <register> Element
  • The <lifetime> Element
  • The <constructor> Element
  • The <property> Element
  • The <method> Element
  • The <param> Element
  • The <dependency> Element
  • The <value> Element
  • The <optional> Element
  • The <array> Element
  • The <extension> Element
  • The <instance> Element
  • The <namespace > Element
  • The <alias> Element
  • The <sectionExtension> Element

The <unity> Configuration Section

The top-level element for the configuration section is defined by the name that you specify in the <configSections> tag when adding it to the configuration file. Typically, the element is <unity>, as shown in the following XML example. However, you can choose another name for this section.

  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>

  <unity xmlns="https://schemas.microsoft.com/practices/2010/unity">
    <alias alias="ILogger" type="MyApp.ILogger, MyApp" />
    <namespace name="MyApp.Implementations" />
    <assembly name="MyApp" />
    
    <container>
      …
    </container>

  </unity>

The following attribute is the only attribute available for the Unity section:

Attribute

Description

Xmlns

XML namespace for this section. Not required for the configuration file to work, but if you want XML IntelliSense support in Visual Studio, set this to https://schemas.microsoft.com/practices/2010/unity. This element is optional.

The following child elements are available for the <unity> section:

Element

Number

Description

<alias>

Many

Creates a type alias. This element is optional.

<namespace>

Many

Adds a namespace to the namespace search list. This element is optional.

<assembly>

Many

Adds an assembly to the assembly search list. This element is optional.

<sectionExtension>

Many

Adds a section extension, which adds new supported elements to the configuration schema. This element is optional.

<container>

Many

A set of container configurations. This element is optional.

The <container> Element

The <container> element contains a set of configurations for a Unity container instance. Within that element, there can be child elements describing type mapping, injection configuration, instance creation, container extensions, or other options made available through any added section extensions. The following table lists the attribute for the <container> element.

Attribute

Description

name

Name of this container configuration. One container element in the section may omit the name attribute; all others must have unique names. The unnamed <container> element is considered the default, and is the one that will be loaded if a container name is omitted when calling container.LoadConfiguration. This attribute is optional. For more information see Loading Configuration File Information.

The following example shows the usage of the <container> element.

<unity xmlns="https://schemas.microsoft.com/practices/2010/unity">
  <container> <!-- default container -->
  … content here ...
  </container>
  <container name="otherContainer">
  ... content here ...
  </container>
</unity>

The following table lists the child elements for the <container> element.

Element

Number

Description

<register>

Many

Registration information for a type. This element is optional.

<instance>

Many

Creates an instance directly in the container. This element is optional.

<extension>

Many

Adds a container extension to the Unity container. This element is optional.

For more information see the following:

  • The <register> Element
  • The <instance> Element
  • The <extension> Element

The <register> Element

The <register> element is the basic building block for any configuration file. It enables you to specify type mappings and injection configuration for a type. If you specify a name, that name is used for the type mapping. If you do not specify a name, it creates a default mapping for the specified types. You can specify a lifetime manager for each mapping. If no explicit lifetime manager is configured for a type, it uses the transient lifetime manager.

The following table lists the attributes for the <register> element.

Attribute

Description

type

The type that is being registered. This is the type that will be requested when calling the Resolve method. This attribute is required.

name

The name of the registration; if omitted the default registration for the type will be created. This attribute is optional.

mapTo

Type which will actually be created and returned when Resolve is called. This sets up a type mapping. It can be a user-defined alias or one of the default aliases. This attribute is optional.

The following example shows the common usage for the <register> element.

<container>
  <register type="MyService"> ... </register> <!-- Default registration for type MyService -->
  <register type="ILogger" mapTo="EventLogLogger" /> <!-- type mapping -->
  <register type="ILogger" mapTo="PageAdminLogger" name="emergency" /> <!-- named registration -->
</container>

To register a type mapping at run time, use the RegisterType method. The following example registers EventLogLogger at run time.

// Register a default (un-named) type mapping with a transient lifetime
// Specify the registered type as an interface or object type 
// and the target type you want returned for that type
myContainer.RegisterType<ILogger, EventLogLogger>();
' Register a default (un-named) type mapping with a transient lifetime
' Specify the registered type as an interface or object type 
' and the target type you want returned for that type
myContainer.RegisterType(Of ILogger, EventLogLogger)()

For more information on registering a type at run time see Registering Types and Type Mappings.

The following table lists the child elements for the <register> element. When using interception configuration extension, Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, additional elements are valid children of a <register> element. For more information see Interception Configuration Schema Elements.

Element

Number

Description

<lifetime>

One

The type that manages instances created by the container. This element is optional.

<constructor>

One

Configures the constructor to be called when creating instances. This element is optional.

<property>

Many

Configures properties that will be set when creating instances. This element is optional.

<method>

Many

Configures methods that will be called when creating instances. This element is optional.

For more information see the following:

  • The <lifetime> Element
  • The <constructor> Element
  • The <property> Element
  • The <method> Element

The <lifetime> Element

The <lifetime> element specifies which lifetime manager will be used to manage instances created for a type. If omitted, lifetime defaults to the TransientLifetimeManager. See Understanding Lifetime Managers for details about lifetime managers. The following example shows the common usage for the <lifetime> element

<register type="ILogger" mapTo="SerialPortLogger">
  <!-- Simple use of lifetime - singleton instance -->
  <lifetime type="singleton" />
</register>
<register type="TypeWithCustomLifetime">
<!-- Use a Lifetime manager instance created by a type converter. 
     Type converter gets passed extra information provided in
     in value attribute -->
  <lifetime type="SessionLifetimeManager" 
            value="Session#1" typeConverter="SessionLifetimeConverter" />
</register>

The following table lists the attributes for the <lifetime> element.

Attribute

Description

type

The type of the lifetime manager to create. Type must derive from LifetimeManager. Can be a user-defined alias or one of the default aliases. This attribute is required.

typeConverter

The type of type converter to use when creating the lifetime manager. If given, the type converter’s ConvertFrom method will be called to create the lifetime manager, and pass the contents of the value attribute. If not specified, the default converter for the specified type is used. Aliases are allowed. This attribute is optional.

value

Any value required to initialize the lifetime manager. This attribute is optional.

The <lifetime> element has no valid child elements.

The <constructor> Element

The **<constructor>**element configuration for the constructor for this type and contains details of the constructor injection requirements for this object type. The constructor element has no attributes. You can include only one <constructor> element in each register section. The example shows the common usage for the <constructor> element.

<register type="ILogger" mapTo="SerialPortLogger">
    <!-- Call the constructor with one parameter named "port" -->
    <constructor>
        <param name="port" value="COM1:" />
    </constructor>
</register>

The following table lists the child element for the <constructor> element.

Element

Number

Description

<param>

Many

Specifies the parameters of the constructor to call. If no <param> child elements are present, it indicates that the zero-argument constructor should be called. This element is optional.

For more information see The <param> Element.

You can specify a constructor for the injection of a specific named instance. In the following example, InjectionConstructor indicates****which constructor to use based on its arguments, the string "UI," and causes the TraceSourceLogger constructor with a single string parameter to be invoked.

container.RegisterType<ILogger, TraceSourceLogger>(
            "UI",
            new InjectionConstructor("UI"));
container.RegisterType<DriveController>(
          new InjectionProperty("MyProperty"));
container.RegisterType<DriveController>(
           new InjectionMethod("InitializeMe", 42.0, 
           new ResolvedParameter(typeof(ILogger), "SpecialLogger")));
container.RegisterType(Of ILogger, TraceSourceLogger) _
    ("UI", New InjectionConstructor("UI"))
container.RegisterType(Of DriveController) _
    (New InjectionProperty("MyProperty"))
container.RegisterType(Of DriveController) _
    (New InjectionMethod ( _
        "InitializeMe", _
        42, _
        New ResolvedParameter(GetType(ILogger), "SpecialLogger")))

For more information on using injection at run time see Registering Injected Parameter and Property Values.

The <property> Element

The **<property>**element configures a property for injection. It contains details of the property injection requirements for this object type. You can include one or more **<property>**elements in each <register> element. See Specifying Values for Injection for details on how to specify what value to inject for the property. No explicit value means to inject the default value for the type of the property.

<register type="ILogger" mapTo="SerialPortLogger">
    <!-- Inject the property "Settings" -->
    <property name="Settings" />
</register>

The following table lists the attributes for the <property> element.

Attribute

Description

name

The name of the property. This attribute is required.

dependencyName

If present, resolve the value of the property using this name rather than the default. This attribute is optional.

dependencyType

If present, indicates the type to resolve for the value of the property. If not given, the type of the property is the one resolved. This attribute is optional.

value

Value to store in the property. This string is converted to the type of the property using the default TypeConverter for that type. This attribute is optional.

The <property> element can take a single child element, which can be one of the following:

Element

Number

Description

<dependency>

One

Specifies how to resolve the value to store in the property. This element is optional.

<value>

One

Specifies a literal value to be stored in the property. This element is optional.

<optional>

One

Specifies that an optional value should be resolved for the property. This element is optional.

<array>

One

Configures injection of an array value for properties of array types. This element is optional.

For information about the child elements of the <property> element, see the following:

  • The <dependency> Element
  • The <value> Element
  • The <optional> Element
  • The <array> Element

The <method> Element

The <method> element configures a method that will be called as part of creating an instance. It contains details of the method injection requirements for this object type. You can include one or more <method> elements for each <register> element.

<register type="MyLogger">
    <method name="Initialize">
        <param name="loggerSettings" />
    </method>
</register>

The following table lists the attributes for the <method> element.

Attribute

Description

name

The name of the method to call. This attribute is required.

The <method> element can take the following child elements. These correspond to the parameters of the method you want to specify.

Element

Number

Description

<param>

Many

Specifies the parameters of the method to call. If no <param> child elements are present, it means that the method has no arguments This element is optional.

For more information see the <param> element.

The <param> Element

The <param> element specifies a parameter for constructor or method injection. It is used to determine which constructor or method overload is called, based on the names (and optionally types) of the parameters for the constructor or method.

<constructor>
    <param name="param1" />
    <param name="param2" value="Hello World!" />
</constructor>

See Specifying Values for Injection for more information about how the values for the parameters are provided.

The following table lists the attributes for the <param> element.

Attribute

Description

name

The name of the parameter. This attribute is required.

type

The type of parameter. This attribute is only required if there are two different overloads with the same parameter name and you need to differentiate between them based on type. Normally, the parameter name alone is sufficient. This attribute is optional.

dependencyName

Name to use to resolve dependencies. This attribute is optional.

dependencyType

The type of dependency to resolve. This attribute is optional.

value

Value to inject for this parameter. This attribute is optional.

The <param> element can take one of the following child elements. Only one child element is allowed.

Element

Number

Description

<dependency>

One

Resolve value for parameter through the container. This element is optional.

<optional>

One

Resolve optional value through the container. This element is optional.

<value>

One

Gives explicit value to use for parameter value. This element is optional.

<array>

One

If parameter is of an array type, specifies what values to put into the resolved array. This element is optional.

For information about the child elements of the <param> element, see the following:

  • The <value> Element
  • The <dependency> Element
  • The <optional> Element
  • The <array> Element

Value elements are a schema extension point, so other child elements may be allowed depending on which schema extensions are available. See Extending the Unity Configuration Schema.

The <dependency> Element

The <dependency> element is used when a value is to be resolved through the container. By default, with no other configuration, this element results in a callback into the container for the default value of the type of the containing parameter or property. Attributes may be used to customize what is resolved. If the value cannot be resolved, then an exception is thrown at resolve time. The following example shows the common usage for the <dependency> element.

<constructor>
    <param name="param1">
        <dependency name="otherRegistration" />
    </param>
</constructor>

The following table lists the attributes for the <dependency> element.

Attribute

Description

name

The name of the named type or mapping registered in the container to use to resolve this dependency. If omitted, the default registration will be resolved. This attribute is optional.

type

Type to resolve from the container. It must be a type compatible with the type of the parameter or property. If omitted, Unity resolves the type based on the type of the parent parameter or property. This attribute is optional.

The <dependency> element has no valid child elements.

The <value> Element

The <value> element is used to specify a specific value for a parameter or property. This element lets you specify a string that is then passed through a TypeConverter to create the actual object to be injected. If no specific type converter type is given, then the default type converter for the type of parameter or property is used.

The string is converted to an object using the invariant culture; if you wish to use a locale-specific culture you must provide a custom TypeConverter to do so.

The following table lists the attributes for the <value> element.

Attribute

Description

value

The string value to be converted to an object. This attribute is required.

typeConverter

Type of the TypeConverter to use to convert the value to an object. If omitted, the default type converter for the containing parameter or property type will be used. This attribute is optional.

The following example shows the common usage of the <value> element.

<constructor>
    <param name="param1">
        <value value="42" />
    </param>
    <param name="param2">
        <value value="aieou" typeConverter="VowelTypeConverter" />
    </param>
</constructor>

The <value> element has no valid child elements.

The <optional> Element

The <optional> element is used when a value should be resolved through the container but its presence is optional. The container will try to resolve this parameter or property using the types and mappings registered in the container, but if the resolution fails, the container returns null instead of throwing an exception.

The following table lists the attributes for the <optional> element.

Attribute

Description

name

The name of the named type or mapping registered in the container to use to resolve this optional dependency. If omitted the default registration will be resolved. This attribute is optional.

type

The type to use to resolve an optional dependency mapping or registration. Must be a type compatible with the type of the parameter or property. If you do not specify a type, Unity will resolve the type of the parameter or property. This attribute is optional.

<constructor>
    <param name="param1">
        <optional name="otherRegistration" />
    </param>
</constructor>

The <optional> element has no valid child elements.

The <array> Element

The <array> element can be used to customize which elements are returned in the array if a parameter or property is of an array type. See Specifying Values for Injection for more details.

The <array> element takes no attributes.

The <array> element has a collection of zero or more child elements. If there are no child elements, an empty, zero-length array for both generic and non-generic types is injected. If there is more than one child, any value element such as <dependency>, <optional>, or <value> may be used, and each one corresponds to an element in the returned array.

If you want to have the default container behavior for arrays, do not specify the <array> element; use the <dependency> element instead.

The following example shows the common usage of the <array> element.

<register type="ILogger" mapTo="NetworkLogger">

    <!-- Empty array -->
    <property name="noSettings"> 
       <array />
    </property>

    <!-- Type NetworkSettings[], get default array injection -->
    <property name="allSettings" />

    <!--Type NetworkSettings[], get only the specified three values -->
    <property name="someSettings">
        <array>
            <dependency name="fastSettings" />
            <optional name="turboSettings" />
             <value value="port=1234;protocol=tcp;timeout=60”
                typeConverter="ConnectionSettingsTypeConverter" />
        </array>
    </property>
</register>

The <extension> Element

The <extension> element is used to add a Unity container extension to a container and contains the list of extensions to register with the Unity container.

The following example shows the common usage for the <extension> element.

<container>
    <extension type="Microsoft.Practices.Unity.Interception.InterceptionExtension, Microsoft.Practices.Unity.Interception" />
</container>

The following example adds an extension at run time. This code creates a new instance of an extension class named MyCustomExtension that you have previously created, and which resides in this or a referenced project, and adds it to the container.

IUnityContainer container = new UnityContainer();
container.AddNewExtension<MyCustomExtension>();
Dim container As IUnityContainer = New UnityContainer()
container.AddNewExtension(Of MyCustomExtension)()

For more information on adding extensions at run time see Registering Container Extensions.

The following table describes the single attribute for the <extension> element.

Attribute

Description

type

The type of extension to add to the container. Can be a user-defined alias or one of the default aliases. This attribute is required.

There are no child elements for the <extension> element.

The <instance> Element

The <instance> element is used to specify a value to be placed in the container and to indicate that you do not want that value to be created by the container but that it will be created by using a TypeConverter and then placed in the container by using the RegisterInstance method.

Instances added through configuration tend to be simple because it is hard to represent them with a string value, but they could be arbitrarily complex if there is a type converter that can handle the conversion from a string.

Note

You cannot use an existing instance with the <instance> element. The <instance> section results in the creation of a new instance, much like something registered with RegisterType would. This is in contrast to the use of RegisterInstance, which requires the user to create the instance manually and then register it.

The following table lists the attributes for the <instance> element.

Attribute

Description

name

The name to use when registering this instance. This attribute is optional.

type

The type of the value. Can be a user-defined alias or one of the default aliases. If omitted, the assumed type is System.String. This attribute is optional.

value

The value to pass to the type converter to create the object. If omitted, null is passed to the type converter. This attribute is optional.

typeConverter

The type converter to use to construct the value. If not specified, the default converter for the type of the value is used. This attribute is optional.

The following example shows how the <instance> element is used in a configuration file.

<container>
    <!-- A named string value -->
    <instance name="NorthwindDb" value="SqlConnectionStringHere" />

    <!-- A typed value -->
    <instance type="ConnectionSettings" value="port=1234" typeConverter="ConnectionSettingsTypeConverter" />
</container>

The following example shows how you can register instances at run time. The following example creates a default (unnamed) registration for an object of type EmailService that implements the IMyService interface.

EmailService myEmailService = new EmailService();
myContainer.RegisterInstance<IMyService>(myEmailService);
Dim myEmailService As New EmailService()
myContainer.RegisterInstance(Of IMyService)(myEmailService)

The <instance> element has no child elements.

The <namespace> Element

The <namespace> element is used to declare namespaces that will be automatically searched for types, as explained in the section Specifying Types in the Configuration File.

The following table lists the attribute for the <namespace> element.

Attribute

Description

name

The name of the namespace that is to be searched for the types. This attribute is required.

The following example shows how the <namespace> element is used.

<namespace name="ObjectsInstancesExamples.MyTypes" />

See Specifying Types in the Configuration File for more examples.

The <namespace> element has no allowed child elements.

The <assembly> Element

The <assembly> element is used to declare assemblies that Unity will automatically search for types, as described in the section Specifying Types in the Configuration File.

The following table lists the attribute for the <assembly> element.

Attribute

Description

name

The name of the assembly to search. The assembly name must be sufficiently qualified for the common language runtime (CLR) to load it. Assemblies in the GAC, for instance, must have a fully-qualified assembly name. This attribute is required.

The following example shows how the <assembly> element is used. See Specifying Types in the Configuration File for more examples.

<assembly name="ObjectsInstancesExamples" />

See the Automatic Type Lookup section for the search rules for matches.

The <assembly> element has no allowed child elements.

The <alias> Element

The <alias> element is used to define a type alias, as explained in the section Specifying Types in the Configuration File.

The following table lists the attributes for the <alias> element.

Attribute

Description

alias

The alias used to refer to the specified type. This attribute is required.

type

The type that the alias refers to. This name must be a CLR type name. Aliases or automatic type lookups do not apply with this attribute. This attribute is required.

The following example shows how the <alias> element is used.

<unity>
    <alias alias="MyLogger" type="MyNamespace.MyLogger, MyProject" />
    <alias alias="AGenericType" type="MyNamespace.MyGenericType`1, MyProject" />
</unity>

The <alias> element has no valid child elements.

The <sectionExtension> Element

The <sectionExtension> element is used to load a schema extension. Unlike the <extension> element, which is used to load a container extension object to modify the run-time behavior of a Unity container instance, this element loads a schema extension, which modifies the allowed elements in the configuration file itself. This is a section-level element; it must occur outside any <container> elements.

See Extending the Unity Configuration Schema for more details.

The following table describes the attributes for the <sectionExtension> element.

Attribute

Description

type

The type that implements the section extension. This attribute is required.

prefix

Specifies a prefix that will be appended to all the extension elements. This allows you to avoid collisions if two different extensions add an element with the same name. If left out, no prefix will be added. This attribute is optional.

<unity>
    <sectionExtension type="MyProject.MySectionExtension, MyProject" />

    <sectionExtension prefix="ext" type="MyOtherSectionExtension" />
    ...
</unity>

The <sectionExtension> element has no allowed child elements.

Next Topic | Previous Topic | Home | Community