Posts tagged Patterns

Using a Container To Make a Better Factory

Lately I have been delegating a lot to containers.  If you consider what containers can provide, there are a lot of ways you can leverage them.  Let’s consider the case where you have a Factory implemented using a traditional Factory Pattern to create concrete instances of an abstract type like an interface or base class.

The most common use of the factory pattern involves a switch statement where you say something like “Switch key Case A return new TypeA()”.  Factories are a great way to defer object creation but part of the problem with a factory is that it is very much coupled to the objects it creates and the values used to determine which object to create.  This can be considered as acceptable since you know the factory has a dirty job.  However, let’s consider how we can eliminate the need for switch statements in a factory and let the container do the work.

Most containers support adding objects with a name or key; commonly referred to as a named instance.  This behavior is what we will leverage to make a “better factory.”

Consider this traditional factory (Figure 1)

    public class WidgetRepositoryFactory
    {
        public IWidgetRepository Create(string repositoryKey)
        {
            switch (repositoryKey.ToLower())
            {
                case "xml" :
                    return new WidgetXmlRepository();
                case "csv":
                    return new WidgetFileRepository();
                default :                     throw new ArgumentException("Invalid repositoryKey");
            }
        }
    }

Nothing fancy.  Our traditional factory can provide either an Xml Repository or File Repository.  The repositoryKey could come from a configuration value or even a parameter to some type of request or user input.

Now let’s take a look at a “better factory”.  This example will use StructureMap as the container of choice. 

Note: What this example doesn’t illustrate is how our container bootstraps the application.  To focus on the better factory concept just assume a valid container is populated and provided to the factory when needed. 

Consider our better factory (Figure 2)

    public class WidgetRepositoryBetterFactory
    {
        private readonly IContainerProvider _containerProvider;

        public WidgetRepositoryBetterFactory(IContainerProvider                containerProvider)
        {
            _containerProvider = containerProvider;
        }

        public IWidgetRepository Create(string repositoryKey)
        {
            return (IWidgetRepository)
                _containerProvider.Resolve                   <IWidgetRepository>(repositoryKey);
        }
    }

Within the Create method we are simply using our container to resolve an instance of the IWidgetRepository by it’s key.  This is a bare bones implementation and is not providing any sanity check on the arguments.  There are a couple ways you could go about that, so I’ll leave it up to your imagination.

The “better factory” is wired up to take an instance of an IContainerProvider which looks like the following:

    public interface IContainerProvider
    {
        object Resolve<T>();
        object Resolve<T>(string key);
    }

We can wire this up in Structure Map like so:

      public StructureMapProvider()
        {
            _container = new Container();
            _container.Configure(x =>
            {
                x.ForRequestedType<IContainerProvider>()                  .TheDefault.IsThis(this);
                x.ForRequestedType<IWidgetRepository>().AddInstances
                    (i => i.OfConcreteType<WidgetFileRepository>()                         .WithName("csv"));
                x.ForRequestedType<IWidgetRepository>().AddInstances
                    (i => i.OfConcreteType<WidgetXmlRepository>()                         .WithName("xml"));
            });
        }

When someone calls our StructureMapProvider’s Resolve<T> method for IContainerProvider, they will be given that instance of the StructureMapProvider.  This can be a little confusing at first, but in cases where you do not want your container to be created multiple times, this allows you to to set up your container to support that.

The important lines to review in the StructureMap configuration are these two:

x.ForRequestedType<IWidgetRepository>().AddInstances
   (i => i.OfConcreteType<WidgetFileRepository>().WithName("csv"));
x.ForRequestedType<IWidgetRepository>().AddInstances
   (i => i.OfConcreteType<WidgetXmlRepository>().WithName("xml"));

As of StructureMap 2.5.2 this is how you can register named instances within the Configure expression.  What I think is a little misleading is that this sounds as though you are creating this as a Singleton by saying “Add an instance of this type, with this name.”  In my testing I found that the instance returned when resolving one of these types is a new instance.  The grammar of the API can be a bit tricky if you are not fully-versed in it.

Containers certainly offer a lot of power and you can delegate a lot to a container.  Hopefully next time you need to leverage a factory you can consider how to make it a “better factory”™.  Enjoy!

Using Dependency Injection Containers Effectively

Out of all the SOLID principles the one I feel the strongest about is Dependency Injection (DI).  The motivational poster Derick Bailey created sums it up the best.  Why are we hard-coding our systems together, making them harder to test, and harder to change?

Containers evolved to support DI at runtime so we could apply inversion of control.  Containers also give us some other things we can leverage besides just keeping track of all those dependencies.  We have to be careful not to go container crazy though!

Containers can manage object lifetimes.  Ever had to write a singleton?  With the availability of containers you almost don’t have to anymore.  Before you write your next singleton, think about letting a container manage that lifetime for you.

Use containers to enforce interface/abstract dependencies. Refer to the motivational poster referenced above.  Do you really want to solder the light to the socket?

Make sure you initialize and maintain the container at the right level.  Ideally your application should have one container to serve all.  In WCF you want this to be at the Service Host level.  In ASP.NET it will be something initialized in global.asax.

Encapsulate your container initialization in a class.  I refer to these classes as “Providers”, ex StructureMapProvider or ContainerProvider (Manager might also work too).  This class should be responsible for initializing the container and maintaining the reference to it.  When you need to change your dependencies there’s one place to make that change.

Use containers to handle abstractions built around third-party dependencies or types you don’t own.  Be careful not to follow this anti-pattern pointed out by Jeffrey Palermo.

Favor code based configuration over .config files. Say what?  Configuration files are great for a lot of things.  By setting up a container in one you may think, “Great, now I can just change the .config to add new types, etc”.  Realistically you are probably never going to do that.  Why do I say this? Because I used to believe that I would use .config that way. And it never happened.

Currently my favorite container is StructureMap.  Your mileage may very and fortunately, there are a lot of choices out there.

The Power of Patterns

Design Patterns have been around for some time now but many of us are still learning how and when to leverage these powerful concepts for engineering software.  Design Patterns have also been the source of backlash for those who have suffered under design pattern crazed architects.  As with any useful tool or concept the balance lies somewhere in the middle.

Patterns exist even when you don’t see them.  If I had to choose a way to describe my early programming career (classic ASP & MS Access/MySql) it would be “DRY” (don’t repeat yourself).  I spent a lot of time doing things to avoid duplicate work.  In ASP this meant lots of include files and shared routines.  This led to some common patterns that I used to tackle certain problems; by no means were these actual design patterns, it was just a way I found to best solve the problems I encountered.  Looking back on that early experience I see how the design patterns could have helped.

When framing the problem if you see a pattern try to leverage it to solve the problem.  Before the holidays the project architect (We’ll call him “Brad”) and I were trying to tackle a problem.  As he was looking at what we were doing he suggested the strategy pattern.  We weren’t sure it was a good fit but it gave us something to look at to help us with the problem.

One of the barriers to understanding patterns is a lack of real-world examples.  If you study the strategy pattern I referred to above you’ll see most of the examples discuss simple calculations, A+B type of stuff.  That is helpful, but what if I have 4 factors that are needed to calculate the price and there is other data we must include with the price, like if there was a discount, etc?  Does that mean I can’t use the strategy pattern?

Patterns require you to generalize and forget about your specific domain.  This is probably the hardest part.  A lot of people think that their situation is totally unique; for the domain it may be, but in reality a lot of people have the same problems.  This is where patterns really help.

One of my goals for 2010 will be to continue studying and applying patterns where they fit.  Some great resources I’m using are:

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.

Dependency Injection: Modularize Your Services and Applications

There are many different patterns for objected oriented development that have emerged over the years.  More often than not I will stumble across one that we are inadvertently using in our services or applications at REJIS.  Most recently I wrote about an approach we use when we need a service client that will take data from a service and transform or adapt it to another format (database, xml model, fixed length file, etc).  At the core of that pattern is dependency injection.

Martin Fowler has an excellent (and lengthy) discussion on Inversion of Control and Dependency Injection which is well worth the read.  Wikipedia defines dependency injection as "…the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency." 

For example lets say that you have an interface, IMyInterface, which Class A depends on for some functionality.  Class B and C both implement IMyInterface making them substitutable for Class A’s dependency.  At runtime, through configuration or programmatically, you can decide which concrete class (B or C) for Class A to use.  Rather than having Class A directly depend on Class B or C you reduce coupling by relying on the interface and then you inject this dependency at runtime.

Interfaces represent one of the best possible abstractions available to an object oriented programmer.  The benefits to using interfaces and dependency injection are numerous:

  • By using an interface you have defined a contract of expected behavior for implementers.
  • Interfaces reduce coupling, allowing for independent unit testing, and multiple implementations of the interface.
  • Code becomes simplified and focused by reducing branching logic and overall lines of code.
  • Changes to the application can potentially be applied at runtime (if this is a web app, windows apps would require closing and reopening) and would not require a recompile of the entire application (if the new implementing class is in another assembly only that assembly needs to be compiled).
  • The application will be more "plug and play" and allow for adding or removing functionality as needed.

MSDN has an article that discusses Dependency Injection in depth and how it relates to a few other Creational patterns such as factory.  There are a number of Inversion of Control (IOC) frameworks that assist with dependency injection that use the notion of containers which help manage the lifecycle of objects and apply configuration settings to modify behaviors at runtime.  For a list of open source IOC frameworks check out this post by Scott Hanselman.

Dependency Injection Example – Supporting Multiple Authentication Methods

I have created a sample project which I will use to illustrate the flexibility of this approach.  The sample covers a very common scenario where we must support multiple authentication methods to allow flexibility for our customers.  We’ll look at a traditional approach and then an updated approach that will use Dependency Injection.

At the core of this example is the IAuthenticator Interface and the User Class.  Both are very simple for examples sake.

Public Interface IAuthenticator
    Function Authenticate(ByVal userName As String, _       ByVal password As String) As User
End Interface

Public Class User
    Public Name As String
    Public AuthenticationType As String
    Public IsAuthenticated As Boolean
End Class

The customer requested that the application first be built to support Database Authentication.  Because our architect was thinking ahead and at least forced us to use an interface we will implement that interface in our DatabaseAuthenticator class.

Public Class DatabaseAuthenticator
    Implements IAuthenticator

    Public Function Authenticate(ByVal userName As String, _
      ByVal password As String) As User Implements IAuthenticator.Authenticate
        Dim user As New User
        user.AuthenticationType = "DatabaseAuthentication"
        'Simulate DB authentication
        If userName = "Test" AndAlso password = "Testing!" Then
            user.IsAuthenticated = True
            user.Name = userName
            'else
            'could throw security exception or any other action here.
        End If

        Return user
    End Function
End Class

To test our authentication we’ll go "old school" with a little console program action.  The console program will display a username prompt and password prompt then it will invoke our IAuthenticatorInstance to perform the authentication. 

Let’s first look at life without dependency injection:

Module Module2

    Sub Main()
        Dim authenticator As Authenticator.IAuthenticator

        Select Case My.Settings.AuthenticationType
            Case "Database"
                authenticator = New Authenticator.DatabaseAuthenticator
            Case Else
                Throw New ArgumentException("Invalid AuthenticationType!")
        End Select

        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

In order for Module2 to work we’ve had to hard-code a string value in our case statement to help us decide the type we want to create.  From there we instantiate the appropriate class manually.  This works fine; it will run and there are no problems with it…until you need a new authentication method.  Then you must go back and add a new class that implements IAuthenticator, add a branch to the Case statement and then instantiate your new class.  Of course you could do this without interfaces as well…but I digress. 

On to life with dependency injection:

Module Module1

    Sub Main()
        Dim authenticatorType As System.Type = _
         Type.GetType(My.Settings.AuthenticatorType)
        Dim authenticator As Authenticator.IAuthenticator = _
         Activator.CreateInstance(authenticatorType)
        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

You probably noticed the first line where we dim up the authenticator variable by calling Activator.CreateInstance and passing it a type variable which I resolved using the Type.GetType method.  Type.GetType(string) returns the System.Type which we can then pass to activator to get our instance created.

Our settings file contains this section:

<applicationSettings>
    <DepdencyInjectionConsole.My.MySettings>
        <setting name="AuthenticatorType" serializeAs="String">
            <value>Authenticator.DatabaseAuthenticator, Authenticator</value>
        </setting>
    </DepdencyInjectionConsole.My.MySettings>
</applicationSettings>

The notation I used for the type information is the standard "Class, Assembly".  Note that I am not using strong names so it is not necessary to include version and public key information.  Also note that none of the code in Module 1 references the concrete class DatabaseAuthenticator.

You may have also noticed that, including whitespace, Module1 has 29 lines versus Module2’s 36 lines of code (excluding line continuations).  In our simple example 7 lines isn’t much but in complex systems that factor could be easily multiplied by 10 or more.

The code that was written for Module1 has no dependencies other than it has to know about Authenticator.IAuthenticator.  The true dependency is injected at runtime.  If we try to use a type in the AuthenticatorType setting that the system cannot resolve then our program will blow up. 

Which leads us to the paradigm shift; you have to be aware of your operating environment and ensure that the assemblies you need are available in the GAC or in your applications executing or bin folder (for web apps and IIS hosted services).  This does not negate managing your dependent assemblies but it shifts it from something necessary throughout development to something that could potentially only happen during deployment.  Because the code only depends on the Interface IAuthenticator two completely different teams could be coding the main module and an IAuthenticator implementation.  Development for Module2 is more susceptible to breaking changes because of direct dependencies on the classes that implement IAuthenticator.

Adding Another Authenticator Implementation

The customer you wrote this system for now wants to add authentication that will read an XML document for user accounts.  We create a new assembly called CustomAuthenticator and our new class looks like this:

Public Class XmlAuthenticator
    Implements Authenticator.IAuthenticator
    Private Shared authenticationStore As Xml.Linq.XDocument

    Sub New()
        authenticationStore = _
        Xml.Linq.XDocument.Load("C:\Temp\AuthenticationStore.xml")
    End Sub

    Public Function Authenticate(ByVal userName As String, _
      ByVal password As String) As Authenticator.User _
      Implements Authenticator.IAuthenticator.Authenticate

        Dim user As New Authenticator.User
        Dim userQuery = From u In authenticationStore...<users>...<user> _
         Where u...<name>.Value = userName _
         And u...<password>.Value = password _
         Select u

        user.AuthenticationType = "XmlAuthentication"
        user.IsAuthenticated = userQuery.Count = 1
        If user.IsAuthenticated Then
            user.Name = userName
        End If

        Return user
    End Function
End Class

The XmlAuthenticator uses an XML file to store user accounts and loads in its constructor.  Using LINQ we query the XML document to find if our user exists.  This class resides in a completely separate assembly. 

If you are adept at reading LINQ XML Queries you can guess the documents structure:

<?xml version="1.0" encoding="utf-8" ?>
<users>
    <user>
        <name>Test</name>
        <password>Testing!</password>
    </user>
</users>

Adding XmlAuthenticator to Module2 (Anti-Dependency Injection Module)

In order to implement this in Module2 we need to add a branch to our case statement:

Case "XML"
    authenticator = New CustomAuthenticator.XmlAuthenticator

Total cost – two lines of code, another hard-coded string, someone has to update the config file and deploy the new assembly.

Adding XmlAuthenticator to Module1 (Pro-Dependency Injection Module)

In order to implement this in Module1 we need to…do nothing.  Not programmatically anyhow, but we do need to update our AuthenticatorTypeValue in the app.config.

Here’s the new config:

<applicationSettings>
    <DepdencyInjectionConsole.My.MySettings>
        <setting name="AuthenticatorType" serializeAs="String">
            <value>CustomAuthenticator.XmlAuthenticator, CustomAuthenticator</value>
        </setting>
    </DepdencyInjectionConsole.My.MySettings>
</applicationSettings>

Total cost – zero lines of code and someone has to update a config file and deploy the new assembly.  Less work and less code to maintain.  Ladies and gentlemen I think we have a winner here!

This is a very simple example that hopefully illustrated what you can achieve using dependency injection.  The code is simply for illustration and I do not recommend or condone anyone using for their authentication components (nor will I be liable for anything you do with this)!

What are some real world ways we use this?

For service clients where we are responsible for retrieving data from a service and doing something with it we use dependency injection for what we our "adapters".  The adapters take a known type from a service and do whatever is needed; store data in a database, flat file, or another XML format.

For a service we are developing on a statewide data sharing project dependency injection is being used to allow for a custom implementation of activities within that service so that the service can be deployed to another geographical region in the state and customized via configuration.  The major functionality points were identified and abstracted with interfaces so the functionality could be implemented in different ways for the two regions.  This also allows a separate code base that the other region can maintain and update as needed.  The core functionality is completely similar between each region and should require no modification except any bugs that may surface.

We will also use this approach on another service to allow a custom "path" for a document that we will receive from an external source.  We have cases where, depending on what external partner sends us information, we need to do multiple things with it and this can vary from partner to partner.  This last example may require a more sophisticated method so I am leaning towards the Unity Framework from Microsoft as we already use Enterprise Library extensively in our services.

Another Tool in the Toolbox

The best way to look at all of these object-oriented approaches is that they are tools in your toolbox.  I will likely not use dependency injection everywhere.  But in the work I do with services we need this pattern more often than not.  Hopefully this gives you enough insight to decide if you may be able to benefit from using it in your own applications.