Support for creating objects using factories

Dec 13, 2008 at 12:32 PM
Hi,

Does Unity supports object instantiation from a custom factory ? I'm trying retrieve a NHibernate ISession instance but these gets created with a factory. Windsor has such support ( see http://blog.codiceplastico.com/?p=143 ).

If Unity does not do out of the box, are there any ready made extension for this ?

Thanks

Simon
Dec 13, 2008 at 2:41 PM
Hi,

Actually I found out later on the web how to do it with StaticFactoryConfiguration (don't why I did not find it sooner). I created a static My class to provide easy access to the container. However the Configure for StaticFactory always returns null. It did that Unity 1.1. I upgraged to 1.2 and it still returns null (see bold line below).

Am I doing this wrong ?

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.StaticFactory;
using Core.Repositories;

namespace Core
{
    /// <summary>
    /// Global point of access to the MS Unity IoC container.
    /// </summary>
    public sealed class My
    {
        private static UnityContainer _container;

        public static UnityContainer Container
        {
            get
            {
                if (_container == null) {
                    _container = new UnityContainer();
                    RegisterTypesInThisAssembly(_container);
                }
                return _container;
            }
        }
       
        /// <summary>
        /// Register all types contained in this assembly.
        /// </summary>
        private static void RegisterTypesInThisAssembly(UnityContainer container)
        {
            IStaticFactoryConfiguration config;
            config = container.Configure<IStaticFactoryConfiguration>();  <=== Returns null
            config.RegisterFactory<UnitOfWork>(unity => PerThreadUnitOfWorkFactory.GetCurrentUnitOfWork());

            container.RegisterType<IUnitOfWork, UnitOfWork>()
            container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
        }
    }
}
Dec 13, 2008 at 6:48 PM
You have to add StaticFactoryExtension before configuring it. Add the following line before call to Configure:

    container.AddNewExtension<StaticFactoryExtension>();  

Regards,
SYS.