Saturday, February 19, 2011

Factory Pattern Using Unity Application Block

I have been working with the Unity Application Block lately and I keep getting learning new things. I wanted to share with you how you could implement the Factory Pattern when you are working with Unity and how it can make your life easier.

With Unity you can have the interfaces and their concrete implementation mappings in the Unity configuration file, giving you great flexibility to map whatever interface you want to their implementation. This way unity container will be able to resolve any contract you pass along.

     /// encapsulates the instantiation of data provider classes
    public static class Factory
    {
        private static readonly string containerName = "DALContainer";
        private static readonly IUnityContainer container;

        static Factory()
        {
            if (String.IsNullOrEmpty(containerName))
            {
                throw new InvalidOperationException();
            }
            container = new UnityContainer().LoadConfiguration(containerName);
        }

        /// Instantiates a data provider class
        public static T CreateProvider < t >()
        {
            return container.Resolve < t >();
        }
    }

Then the only thing you need to do when you need to instantiate your data provider class ask your factory for it:

IUserProvider dataProvider = Factory.CreateProvider < IUserProvider >()

Notice how less code you need to implement the pattern and encapsulate the functionality with the convenience of leveraging the class resolution into a configuration file, which you can change without having to recompile the application !

Hope the tricks help out there.

Cheers!
-arbbot

No comments:

Post a Comment