A day with .Net

My day to day experince in .net

Dependency Injection with Unity and StructureMap in MVC 4

Posted by vivekcek on June 10, 2013

Initial Solution.

1.) Create an MVC 4 Web project.

2.) In the Model folder add a Product class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnityDI.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }
}

3. Create a folder named ‘Repository’ then add an interface ‘IProductRepository’ and its implementation ‘ProductRepository’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityDI.Models;

namespace UnityDI.Repository
{
    public interface IProductRepository
    {
        IList<Product> GetAll();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnityDI.Repository
{
    public class ProductRepository : IProductRepository
    {
        public IList<Models.Product> GetAll()
        {
            throw new NotImplementedException();
        }
    }
}

4. Now create a HomeController as Given below, also add an index view.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UnityDI.Repository;

namespace UnityDI.Controllers
{
    public class HomeController : Controller
    {
        private IProductRepository pdt = null;
        public HomeController(IProductRepository _pdt)
        {
            pdt = _pdt;
        }

        public ActionResult Index()
        {
            return View();
        }

    }
}

5. If you run now you get a an error says that ‘No parametrized constructor for controller’.

How to Configure Unity

1. Go to Nuget and add Unity.MVC4. Which will add the dependency for Unity (for VS2010 WITH .NET 4.0). If you are working with .NET 4.5 you can install Unity 3.0.

unity1

2. On sucessful installation A BootStrapper.cs file will be added to your solution.Change that file by adding.’ container.RegisterType();‘ in BuildUnityContainer() method. The full code is given below.

using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc4;
using UnityDI.Repository;

namespace UnityDI
{
  public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      container.RegisterType<IProductRepository, ProductRepository>();
      RegisterTypes(container);

      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
    
    }
  }
}

3. Now in global.asax under Application_Start()add this code

Bootstrapper.Initialise();

Configure StructureMap.

1. Install Nuget Packge structuremap not StructureMap.Mvc.

2. Add a BootStrapper class as given below. You need ‘StructureMap’ and StructureMap.Configuration.DSL name spaces.

 public class BootStrapper
    {
        public static void ConfigureDependencies()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<ControllerRegistry>());
        }
        public class ControllerRegistry : Registry
        {
            public ControllerRegistry()
            {
                For<IIProductRepository>().Use<ProductRepository>();
            }
        }
    }

3. Create a custom controller factory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StructureMap;
namespace BlogEngine.Web.Infrastructure
{
    public class ProductEngineControllerFactory:DefaultControllerFactory
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as IController;
        }
    }
}

4. Now add the following code under Application_Start() in Global.asax

 ControllerBuilder.Current.SetControllerFactory(new BlogEngineControllerFactory());
            BootStrapper.ConfigureDependencies();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s