This project is read-only.

IoC Integration with Unity

Topics: Web Api
Mar 18, 2011 at 7:09 PM

I've added Unity integration and it seems to be working well. Thought the code might be useful

Step 01 - create a class which implements IInstanceFactory

/// <summary>
    /// Used for overriding the WCF HTTP InstanceFactory
    /// </summary>
    public class Factory : IInstanceFactory
        private readonly IUnityContainer _container;

        public Factory(IUnityContainer container)
            if (container == null) throw new ArgumentNullException("container");
            _container = container;

        public object GetInstance(Type serviceType, InstanceContext instanceContext, Message message)
            return _container.Resolve(serviceType);

        public void ReleaseInstance(InstanceContext instanceContext, object service)
            // no-op

Step 02 - Get HTTP WCF to use the new factory - which itself uses Unity

            // Container
            Container = new UnityContainer();
            new EndOfDayPricesConfigurationInstaller().Install(Container);
            Container.RegisterType<IEndOfDayPricesDal, EndOfDayPricesDal>();
            Container.RegisterType<IEndOfDayPricesResource, EndOfDayPricesResource>();
            // Override the instance factory of WCF HTTP to use the unity container.
            var config = new HttpHostConfiguration();
            config.SetInstanceFactory(new Factory(Container));

            // Add routes
            RouteTable.Routes.AddServiceRoute<EndOfDayPricesResource>("EndOfDayPrices", config);