Tuesday, 26 January 2016

Unity Repository implementation in MVC by separate config source



Install Unity.Mvc4 Container using NuGet Package Manager Console tool as shown below:
 You can also do online search for Unity.Mvc4 Container by navigating to Tools=>Extension and Update=>Online options in Visual Studio 2012 or 2010SP1 and install it.
When it will be installed successfully, you will be find the following references add to your project as shown below:


Global.asax.cs
private static IUnityContainer container;

protected void Application_Start()
{
       ---
       ---
InitializeDependencyInjectionContainer();

}

private static void InitializeDependencyInjectionContainer()
{
    container = new UnityContainerFactory().CreateConfiguredContainer();
    var serviceLocator = new UnityServiceLocator(container);
    ServiceLocator.SetLocatorProvider(() => serviceLocator);
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

UnityContainerFactory.cs
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace MYPROJ.WebUI
{
    public class UnityContainerFactory
    {       
        public IUnityContainer CreateConfiguredContainer()
        {
            var container = new UnityContainer();
            LoadConfigurationOverrides(container);
            return container;
        }

        private static void LoadConfigurationOverrides(IUnityContainer container)
        {
            container.LoadConfiguration("container");
        }
    }
}

UnityDependencyResolver.cs
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace MYPROJ.WebUI
{
    public class UnityDependencyResolver : IDependencyResolver
    {
        private readonly IUnityContainer unity;

        public UnityDependencyResolver(IUnityContainer unity)
        {
            this.unity = unity;
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return this.unity.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                // By definition of IDependencyResolver contract, this should return null if it cannot be found.
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return this.unity.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                // By definition of IDependencyResolver contract, this should return null if it cannot be found.
                return null;
            }
        }
    }
}

Web.config
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity configSource="unity.config" />
</configuration>

unity.config
<unity>
  <typeAliases>
    <typeAlias alias="string" type="System.String, mscorlib" />
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
    <typeAlias alias="perRequest" type="MYPROJ.WebUI.UnityExtensions.UnityHttpContextPerRequestLifetimeManager, MYPROJ.WebUI" />
  </typeAliases>
  <containers>
    <container name="container">
      <types>
        <!--Web UI Services starts-->
        <type type="MYPROJ.WebUI.Authentication.IFormsAuthentication, MYPROJ.WebUI" mapTo="MYPROJ.WebUI.Authentication.DefaultFormsAuthentication, MYPROJ.WebUI">
          <lifetime type="perRequest" />
        </type>
        <!--Web UI Services starts-->

        <!--Domain Model Services starts-->
        <type type="MYPROJ.Data.IApplicationInspectorRepository, MYPROJ.Data" mapTo="MYPROJ.Data.Sql.Repositories.ApplicationInspectorRepository, MYPROJ.Data.Sql ">
          <lifetime type="perRequest" />
        </type>
        <type type="MYPROJ.Domain.Contracts.IMetaDataService, MYPROJ.Domain" mapTo="MYPROJ.Domain.MetaDataService, MYPROJ.Domain">
          <lifetime type="perRequest" />
        </type>
        <type type="MYPROJ.Domain.Contracts.ITerritoryServices, MYPROJ.Domain" mapTo="MYPROJ.Domain.TerritoryService, MYPROJ.Domain">
          <lifetime type="perRequest" />
        </type>
        <type type="MYPROJ.Domain.Contracts.ILogicalMappingServices, MYPROJ.Domain" mapTo="MYPROJ.Domain.LogicalMappingsServices, MYPROJ.Domain">
          <lifetime type="perRequest" />
        </type>
        <!--Domain Model Services ends-->
      </types>
    </container>
  </containers>
</unity>

HttpContextPerRequestStore.cs
using System;

namespace MYPROJ.WebUI.UnityExtensions
{
    public class HttpContextPerRequestStore : IPerRequestStore
    {
        public HttpContextPerRequestStore()
        {
            if (HttpContext.Current.ApplicationInstance != null)
            {
                // Note: We'd like to do this, but you cannot sign up for the EndRequest from
                // from this application instance as it is actually different than the one the
                // the EndRequest handler is actually invoked from.
                //HttpContext.Current.ApplicationInstance.EndRequest += this.EndRequestHandler;
            }
        }

        public object GetValue(object key)
        {
            return HttpContext.Current.Items[key];
        }

        public void SetValue(object key, object value)
        {
            HttpContext.Current.Items[key] = value;
        }

        public void RemoveValue(object key)
        {
            HttpContext.Current.Items.Remove(key);
        }

        private void EndRequestHandler(object sender, EventArgs e)
        {
            EventHandler handler = this.EndRequest;
            if (handler != null) handler(this, e);
        }

        public event EventHandler EndRequest;
    }
}

UnityHttpContextPerRequestLifetimeManager.cs
namespace MYPROJ.WebUI.UnityExtensions
{
    /// <summary>
    /// The UnityHttpContextPerRequestLifetimeManager exists solely to make it easier
    /// to configure the per-request lifetime manager in a configuration file.
    /// </summary>
    /// <remarks>
    /// An alternative approach would be to use a type converter to convert the
    /// configuration string and new up a <see cref="UnityPerRequestLifetimeManager"/>
    /// from this type converter.
    /// </remarks>
    public class UnityHttpContextPerRequestLifetimeManager : UnityPerRequestLifetimeManager
    {
        public UnityHttpContextPerRequestLifetimeManager() : base(new HttpContextPerRequestStore())
        {
        }
    }
}



No comments:

Post a Comment