Thursday, 30 April 2015

Setting Up Unity

> C#/.Net Samples

Set Up IUnityContainerAccessor

using Microsoft.Practices.Unity;
 
namespace Project.Core.DI
{
    public interface IUnityContainerAccessor
    {
 
        #region MEMBERS
 
        /// <summary>
        /// Gets the container.
        /// </summary>
        /// <value>The container.</value>
        UnityContainer Container { get; }
 
        #endregion
 
    }
}

Set Up Bootstrap

This is where you'll tie the class to the interface. You'll also need to call this method in your Global file. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
 
namespace Project.Core.DI
{
    public partial class UnityBootstrapper
    {
 
        #region METHODS
 
        public static void ConfigureContainer(UnityContainer container)
        {
            if (container == null)
                container = new UnityContainer();
 
            container.RegisterType<IUserService, UserService>();
 
        }
 
        #endregion
 
    }
}

Set Up ErrorHandlingActionInvoker

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
 
namespace Project.MvcBase
{
    public class ErrorHandlingActionInvoker : ControllerActionInvoker
    {
 
        #region DECLARATIONS
 
        private readonly IExceptionFilter filter;
 
        #endregion
        
        #region CONSTRUCTORS
 
        public ErrorHandlingActionInvoker(IExceptionFilter filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }
 
            this.filter = filter;
        }
 
        #endregion
 
        #region OVERRIDES
 
        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filterInfo =
            base.GetFilters(controllerContext,
            actionDescriptor);
 
            filterInfo.ExceptionFilters.Add(this.filter);
 
            return filterInfo;
        }
 
        #endregion
        
    }
 
}

Set up UnityControllerFactory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
using Microsoft.Practices.Unity;
using Project.Core.DI;
 
namespace Project.MvcBase
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
 
        #region OVERRIDE METHODS
 
        /// <summary>
        /// Retrieves the controller instance for the specified request context and controller type.
        /// </summary>
        /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
        /// <param name="controllerType">The type of the controller.</param>
        /// <returns>The controller instance.</returns>
        /// <exception cref="T:System.Web.HttpException">
        ///  <paramref name="controllerType"/> is null.</exception>
        /// <exception cref="T:System.ArgumentException">
        ///  <paramref name="controllerType"/> cannot be assigned.</exception>
        /// <exception cref="T:System.InvalidOperationException">An instance of <paramref name="controllerType"/> cannot be created.</exception>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            IController controller = null;
 
            
            if (controllerType != null)
            {
                if (typeof(IController).IsAssignableFrom(controllerType))
                {
                    try
                    {
                        IUnityContainerAccessor containerAccessor = requestContext.HttpContext.ApplicationInstance as IUnityContainerAccessor;
                        controller = containerAccessor.Container.Resolve(controllerType) as IController;
                        var c = controller as Controller;
                        if (c != null)
                        {
                            //TIE global error handle attribute, if not doing via FilterConfig.cs
                            //c.ActionInvoker = new ErrorHandlingActionInvoker(new CustomHandleErrorAttribute()); //HandleErrorWithElmahAttribute()
                        }
                    }
                    catch (Exception ex)
                    {
                        //ErrorSignal.FromCurrentContext().Raise(ex);
                        throw new HttpException(404, String.Format("Error resolving controller {0}", controllerType.Name), ex);
 
                    }
                }
            }
            else
            {
                throw new HttpException(404,
                    String.Format("The controller for path '{0}' could not be found or it does not implement IController.",
                        requestContext.HttpContext.Request.Path));
 
            }
            
            return controller;
        }
 
        #endregion
 
    }
}


Use In Controllers

#region PROPERTIES
 
        [Dependency]
        public IUserService UserServiceInstance { get; set; }
 
        
        #endregion


UserServiceInstance.SomeMethod();

Use in Class Library


#region PROPERTIES
 
        private IUserService UserServiceInstance { get; set; }
 
        #endregion


and place this inside class constructor

IUnityContainerAccessor accessor = (HttpContext.Current.ApplicationInstance as IUnityContainerAccessor);
 
UserServiceInstance = accessor.Container.Resolve<IUserService>();