This project is read-only.

Unity Service Behavior

Assembly  EnterpriseLibraryExtensions.Unity.ServiceModel.dll
Namespace   EnterpriseLibraryExtensions.Unity.ServiceModel
 Class  UnityServiceBehavior 

The Unity Service Behavior class is a behavior that can be registered on a WCF service which then instantiates the WCF service using a Unity container. The behavior can be registered either programmatically in code or by adding the behavior in the configuration file.

Open the quick start sample “UnityServiceBehavior” to see the different options for using Unity with WCF services.


When specifying that a service must be instantiated by Unity, it is necessary to assign a container which handles the dependency injection for the service. The container and the dependencies within that container can be specified using either a named container which will be picked up from the configuration file or by using a globally registered Unity container which is then shared between any services that use this option.

Using the UnityServiceConfiguration class, it is possible to set the global container as well as specify the name of the configuration section where the default and/or named Unity containers are specified in the configuration file.

In Code

Specifying a service to use Unity in code is very easy. Apply the Unity attribute to your service implementation and that’s it.

internal class ServiceWithUnityAttribute : IServiceWithDependency

The Unity attribute has two optional mutually exclusive properties that can be set. These are ContainerName and UseGlobalContainer. Setting UseGlobalContainer to true makes the service resolve it’s dependencies using the global container set on the UnityServiceConfiguration class.

Setting the ContainerName value makes the service resolve dependencies using the container with the provided name. Specifying an empty container name is the same as having no properties set.

By Configuration

Services can also be configured to be instantiated by a Unity container by specifying it in the configuration file. To do this, add a new extension to the system.ServiceModel configuration element.

    <add name="UnityServiceBehavior" type="EnterpriseLibraryExtensions.Unity.ServiceModel.UnityServiceBehavior, EnterpriseLibraryExtensions.Unity.ServiceModel"/>

Then, create or add to a service behavior and specify that it should use the behavior. By using the containerName attribute, the container can be a named container instead of the default one.

<behavior name="UnityNamedContainerServiceBehavior">
  <UnityServiceBehavior containerName="SpecificUnityContainer" />

It is also possible to specify the usage of the global container by using the useGlobalContainer property and setting it to true.

Last edited Apr 18, 2012 at 8:16 PM by RasmusTherkelsen, version 2


No comments yet.