Tuesday, 26 January 2016

Unity Repository implementation in MVC by Web.config



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
public class MvcApplication : HttpApplication
{
    public IUnityContainer Container
    {
        get { return ServiceProvider.Container; }
    }

    protected void Application_Start()
    {
        ---
        ---
        RegisterContracts();           
    }

    public void RegisterContracts()
    {
        //Load the contract information from config file.
        Container.LoadConfiguration("HContainer");
    }
}


ServiceProvider.cs
public sealed class ServiceProvider
{
    private ServiceProvider()
    {
    }

    public static ServiceProvider Instance { get { return Nested.instance; } }
    public static IUnityContainer Container { get { return Nested.Container; } }

    private class Nested
    {
        public static IUnityContainer Container;

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
            Container = new UnityContainer();
        }

        internal static readonly ServiceProvider instance = new ServiceProvider();
    }
}


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

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container name="HContainer">
      <register type="HWebAPI.Handlers.IHotels, HWebAPI" mapTo="HWebAPI.Handlers.STAHandler, HWebAPI" name="STA" />

      <register type="HWebAPI.Handlers.IHotels, HWebAPI" mapTo="HWebAPI.Handlers.CrossSellHandler, HWebAPI" name="CXL" />

      <register type="HWebAPI.Handlers.IHotels, HWebAPI" mapTo="HWebAPI.Handlers.InPathHandler, HWebAPI" name="INPATH" />

      <register type="HBAL.Interface.IDTHotelAdditionalInfoBAL, HBAL" mapTo="HBAL.DTHotelAdditionalInfoBAL, HBAL" />     
      <!-- named registration -->
    </container>
  </unity>



No comments:

Post a Comment