Posts tagged Unity

WCF InstanceContextMode.Single, Default Constructors, and Unity

During a refactoring of a WCF solution I was converting all the various services in the solution to use dependency injection with constructors.  One of the services was configured as a singleton using the ServiceBehavior InstanceContextMode.Single.  This particular service controls a resource that is best left for a singleton because it has an open socket listener that receives responses from our mainframe systems.  The service was also configured for transactions and has the ReleaseServiceInstanceOnTransactionComplete explicitly set to false.

When the other developer on the project fired up the test harness for the services he was receiving the message “The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host. “.  After testing a few theories I noticed that the service was marked up with the InstanceContextMode behavior.  I removed the attribute and tested the service and it worked just fine which lead me to draw a conclusion about how WCF handles the InstanceContextMode attribute.

Because you are telling WCF to manage that service instances lifetime it makes sense that it would require a default constructor because WCF is going to be instantiating and disposing of the service instance.  When I refactored the service with no default constructor that was a breaking change for the WCF infrastructure.  So the question remains, can Unity handle a singleton service instance?

To test Unity with a Singleton service I followed the steps in my previous article on Unity and WCF and created an IInstanceProvider, IServiceBehavior, and a custom ServiceHost.  The results were what I expected.  Each call to the service was handled by the singleton instance of the service whose lifetime was being managed by the Unity container.

using System;

namespace Service
{
    //[System.ServiceModel.ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)]
    public class PersonService : Contracts.IPersonService
    {
        private Guid _instanceId;

        /// <summary>
        /// Initializes a new instance of the PersonService class.
        /// </summary>
        public PersonService()
        {
            _instanceId = Guid.NewGuid();
        }

        #region IPersonService Members

        public Contracts.PersonResponse SavePersonRecord(Contracts.PersonRequest request)
        {
            return new Contracts.PersonResponse(_instanceId.ToString(),                     String.Format("Added Person - {0}", request.Person.Name));
        }

        public Contracts.PersonResponse DeletePersonRecord(Contracts.PersonRequest request)
        {
            return new Contracts.PersonResponse(_instanceId.ToString(),                    String.Format("Deleted Person - {0}", request.Person.Name));
        }

        #endregion
    }
}

Unity_Singleton_Output

The client calls the SavePersonRecord method then subsequently the delete person method.  As you can see the Instance Id returned by the service is the same for both calls.  Removing the lifetime element from the Unity configuration results in two different instance Id’s returning from the service because the default behavior for WCF is to create a new instance per call to the service.

I ran one final test and that was to remove the default constructor and require the Instance Id to be passed to the constructor:

using System;

namespace Service
{
    //[System.ServiceModel.ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)]
    public class PersonService : Contracts.IPersonService
    {
        private Guid _instanceId;

        /// <summary>
        /// Initializes a new instance of the PersonService class.
        /// </summary>
        /// <param name="instanceId"></param>
        public PersonService(string instanceId)
        {
            _instanceId = new Guid(instanceId);
        }

        #region IPersonService Members

        public Contracts.PersonResponse SavePersonRecord(Contracts.PersonRequest request)
        {
            return new Contracts.PersonResponse(_instanceId.ToString(),               String.Format("Added Person - {0}", request.Person.Name));
        }

        public Contracts.PersonResponse DeletePersonRecord(Contracts.PersonRequest request)
        {
            return new Contracts.PersonResponse(_instanceId.ToString(),                String.Format("Deleted Person - {0}", request.Person.Name));
        }

        #endregion
    }
}

The Unity configuration now looks like so:

<unity>
  <typeAliases>
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,         Microsoft.Practices.Unity" />
    <typeAlias alias="IPersonService" type="Contracts.IPersonService, Contracts" />
  </typeAliases>
  <containers>
    <container>
      <types>
        <type type="IPersonService" mapTo="Service.PersonService, Service">
          <lifetime type="singleton" />
          <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,              Microsoft.Practices.Unity.Configuration">
            <constructor>
              <param name="instanceId" parameterType="System.String, mscorlib">
                <value value="2423f423-a4da-4306-9ba1-452214c517d6"/>
              </param>
            </constructor>
          </typeConfig>
        </type>
      </types>
    </container>
  </containers>
</unity>

Hopefully it is no surprise that the results of calling the service are the same as the screenshot posted above.

I still need to test this with transactions but I believe using the right set of options will prevent WCF from disposing your singleton and allow your custom Unity service host to handle that.

Modularizing WCF with Unity

For a new project at work I thought it best to use dependency injection to deal with some complexities we were facing.  I also wanted to get in and do some mocking in our unit tests to get a good feel for that.  Since we use the Enterprise Library I decided it would be easiest to roll with using Unity.  I have previously blogged about using Unity but this would go even further, because we would be injecting a dependency into the constructor of the service as well as injecting dependencies into the service’s core library.

I did quite a bit of homework and reached the conclusion that in order to do this you would need to hook into WCF’s pipeline and override several key areas during the service host creation and service instance creation.  The best article I found to get me started was this one by Steve Moseley.  Steve broke it down into 6 steps:

  1. Creating a custom instance provider that resolves the service
  2. Creating a custom service behavior to plug in the new instance provider
  3. Creating a custom service host that will add the new behavior
  4. Creating a custom service host factory (which configures your Unity Container)
  5. Changing the service host factory in the .svc file
  6. Inject your objects (through configuration)

His instructions were fantastic for steps 1-5 but step 6 left me to think on my own a bit.  The constructor of the new service we were working on needed an instance of its “core” library which will be the real work horse for the service.  Typically our services only provide a gateway into some other functionality so the service layer handles messaging and translation then delegates the work to a core library which can do whatever it needs to. 

This service would also be a little different than most because we would be relying on both internal and external “suppliers” to provide data to our core library.  These suppliers could be in the form of remote web services, local services, or shared assemblies.  Our core library itself will also need it’s dependencies injected at runtime.

Step 6 involved a bit more detailed study of Unity in which I did the following:

  • Defined typeAliases for each of the dependencies I would be injecting
  • Defined type mappings for the simple dependencies which had only a default constructor
  • Defined typeConfigs for the complex dependencies which required other dependencies passed to their constructor

I chose the constructor injection route because the service should not be created without a core library and the core library should not be created without its supplier dependencies and data access layer.  I believe I could have accomplished something similar had I used default constructors and exposed read/write properties for the dependencies.  This would have removed the constructor requirements but potentially caused issues if someone were using this class without supplying the dependencies to the read/write properties.  So, constructor injection wins for now.

In the end the config looked something like this:

<configSections>
  <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>
<unity>
  <typeAliases>
    <!-- Lifetime manager types -->
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <!-- User-defined type aliases -->
    <typeAlias alias="ISupplier" type="MyService.Contracts.ISupplier, MyService.Contracts"/>
    <typeAlias alias="MyService" type="MyService.Service.MyService, MyService.Service"/>
    <typeAlias alias="ICore" type="MyService.Contracts.ICore, MyService.Contracts"/>
  </typeAliases>
  <containers>
    <container>
      <types>
        <type type="ISupplier" mapTo="MyService.Suppliers.ExternalSupplier, MyService.Suppliers" name="ExternalSupplier"/>
        <type type="ISupplier" mapTo="MyService.Suppliers.InternalSupplier, MyService.Suppliers" name="InternalSupplier"/>

        <type type="ICore" mapTo="MyService.Core.MyCore, MyService.Core" name="MyCore">
          <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <constructor>
              <param name="externalSupplier" parameterType="ISupplier">
                <dependency name="ExternalSupplier"/>
              </param>
              <param name="internalSupplier" parameterType="ISupplier">
                <dependency name="InternalSupplier"/>
              </param>
            </constructor>
          </typeConfig>
        </type>

        <type type="MyService" mapTo="MyService.Service.MyService, MyService.Service">
          <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <constructor>
              <param name="myCore" parameterType="ICore">
                <dependency name="MyCore"/>
              </param>
            </constructor>
          </typeConfig>
        </type>
      </types>
    </container>
  </containers>
</unity>  

Once this was working successfully I took a step back to the unit tests project to do some mocking.  I know someone out there is thinking “why would he try that before unit tests?   Couple reasons: 1) This was an entirely new endeavor and its easier for me to get the final concept working 2) The first 5 steps from Steve’s article required some low-level work to hook into WCF.  Rather than unit testing that I decided to flush it out by actually firing up a sample service to work out the kinks.  Next time the unit tests will be done first…

Dependency Injection Part 2: Microsoft’s Unity

In my previous post on dependency injection I discussed a simple way to enable dependency injection using configuration and System.Activator.  The method described would be sufficient for many cases but may not offer enough power for every situation.  This time we will explore the use of an Inversion of Control container, namely Microsoft’s Unity Application Block.

Taking the "another tool in the tool box" approach let’s explore unity using our previous example of a system which requires multiple authentication methods.

I downloaded and installed Microsoft Enterprise Library 4.1 (October 2008) which you can download here.  If you do not need the entire Enterprise Library (EL) then you can download the standalone Unity Application Block here.  I highly recommend trying out the EL because it has a lot of very useful application blocks for common needs of enterprise developers.

The benefits of using a more powerful framework such as Unity are that you get additional features such as simplified object creation and lifetime management (can register objects as singletons) in addition to the other benefits of looser coupling and more flexibility.  You can also use caching to store containers and then retrieve them when you need to access it again.

I will be using the same solution and project as my previous post and we will start by adding a reference to the Unity assembly.  The first method I will use is to manually register types with the unity container.  The second will be using configuration to specify the container’s configuration and types to use.  The ultimate bench mark for me will be to determine which method uses the least amount of code and leaves us with the most flexibility to make changes.

Manually Building and Registering Objects with the Container

Following the guidance in "Setting Up the Unity Container" I came up with this code:

Module Module3

    Sub Main()
        Dim container As Microsoft.Practices.Unity.IUnityContainer = _
        New Microsoft.Practices.Unity.UnityContainer

        container.RegisterType(Of Authenticator.IAuthenticator,  _
        Authenticator.DatabaseAuthenticator)()

        Dim authenticator As Authenticator.IAuthenticator = _
         container.Resolve(Of Authenticator.IAuthenticator)()
        Dim userName As String
        Dim password As String
        Dim user As Authenticator.User

        Console.WriteLine("Username: ")
        userName = Console.ReadLine

        Console.WriteLine("Password: ")
        password = Console.ReadLine

        Console.Clear()

        user = authenticator.Authenticate(userName, password)

        If user.IsAuthenticated Then
            Console.WriteLine(String.Format("User authenticated via {0}!", _
              user.AuthenticationType))
        Else
            Console.WriteLine("User authentication failed!")
        End If

        Console.ReadLine()
    End Sub

End Module

This was a pretty basic setup and the learning curve was almost zero.  I was already using a similar method to set up my own dependency injection and this was a very natural seeming approach.  However, I am not entirely satisfied with this approach as it has constrained us to making code changes and recompiling to switch to a new implementation of IAuthenticator. 

Now this was a very basic and simple example so I wouldn’t say this is a fault of Unity but more a fault of me just doing the bare minimum to create a container and add an object to it.

Configuring a Container Using Configuration Files

Let’s look at using Unity’s configuration schema.

The big disappointment I had so far is that there does not appear to be a visual configuration tool.  I know, how sad, but I do like having those tools available as I think they can help reduce little mistakes you can make when editing XML.  The broader EL configuration tool is very handy and now that I am used to the structures it creates for things like logging and validation it is very easy to use.

After reading "Entering Configuration Information" and some trial and error I developed Module4 which will use a configuration to define the container.

Module Module4

    Sub Main()
        Dim container As Microsoft.Practices.Unity.IUnityContainer = _
        New Microsoft.Practices.Unity.UnityContainer

        Dim section As _          Microsoft.Practices.Unity.Configuration.UnityConfigurationSection _
          = CType(Configuration.ConfigurationManager.GetSection("unity"),  _
          Microsoft.Practices.Unity.Configuration.UnityConfigurationSection)
        section.Containers.Default.Configure(container)

        Dim authenticator As Authenticator.IAuthenticator = _
         container.Resolve(Of Authenticator.IAuthenticator)()
        Dim userName As String
        Dim password As String
        Dim user As Authenticator.User

        Console.WriteLine("Username: ")
        userName = Console.ReadLine

        Console.WriteLine("Password: ")
        password = Console.ReadLine

        Console.Clear()

        user = authenticator.Authenticate(userName, password)

        If user.IsAuthenticated Then
            Console.WriteLine(String.Format("User authenticated via {0}!", _
              user.AuthenticationType))
        Else
            Console.WriteLine("User authentication failed!")
        End If

        Console.ReadLine()
    End Sub

End Module

After adding the required configSection the unity configuration block looks like so:

<unity>
    <typeAliases>
        <!-- User-defined type aliases -->
        <typeAlias alias="IAuthenticator"
             type="Authenticator.IAuthenticator, Authenticator" />
    </typeAliases>
    <containers>
        <container>
            <types>
                <!-- Type mapping using aliases defined above -->
                <type type="IAuthenticator"
                      mapTo="CustomAuthenticator.XmlAuthenticator,
                      CustomAuthenticator" />
            </types>
        </container>
    </containers>
</unity>

I used the alias feature to create an alias name for the IAuthenticator.  This lets you reference it by alias rather than including the full type information every time you are mapping an instance of the type.

In this example I rewrote the same program I was using for my simple dependency injection to use the Unity Application Block.  The code changes amounted to about 5 lines of code for the simple use of Unity and 6 to use configuration.  The code to use unity was very plain and had no real branching logic in it so it could easily be abstracted to a helper class that would assist in creating the container and returning the instance to the caller.

The flexibility that you can gain by moving to a IOC framework such as Unity is very impressive.  Overall I think this will be beneficial to use as a more robust way to enable dependency injection. 

Next time I will cover a more real world example using Unity in the adapter pattern we use for our WCF service clients.  The basic model is that our service client calls the service and then initializes an instance of a "IMessageAdapter" and calls its Transform method.  The purpose of the adapter is to take the data in the services format and transform or adapt it to something else like a database, fixed length file, etc.  We use this model because it allows us to fully reuse the client and only requires that we create a new implementation of the Interface.