Click here to Skip to main content
15,881,424 members
Articles / Web Development / ASP.NET
Tip/Trick

Unity Dependency Injection with N-Layer Project

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
25 Nov 2016CPOL1 min read 18.3K   10   1
How to use dependency injection in ASP .NET MVC N-Layer Architecture?

Introduction

This article explains how we should extend Unity Container to register type mapping for classes not accessible to registration module.

Scenario

When it comes to implement dependency injection to existing solution, you might have a different layer which you need to inject dependencies for. In my project, I had a requirement to register data layer dependencies from Web project. As its data layer, I cannot reference Data Layer libraries to Web project. Below is the approach we are following to overcome this. Please suggest any other better approach to get this done.

The given approach uses UnityContainerExtention created in middle layer and registers it in the first layer.

Using the Code

Once you have added Unity.mvc to your project, App_Start folder will get 2 files UnityConfig.cs and UnityWebActivator.cs added for Unity Container configuration and initiation. If you are new to dependency injection, please check this article for details.

Web Layer: Controller Action Method

C#
//Home controller gets message from business layer
using System.Web.Mvc;
using CodeSlice.Business.Interface;
public class HomeController : Controller
{
    private readonly IDummy _businessDummy;
    public HomeController(IDummy businessDummy)
    {
        _businessDummy = businessDummy;
    }
    public ActionResult About()
    {
       ViewBag.Message = _businessDummy.GetMessage();
       return View();
    }
}

Business Layer

C#
//Business Interface
namespace CodeSlice.Business.Interface
{
    public interface IDummy
    {
        string GetMessage();
    }
}
C#
//Business Layer implementation depends on repository or Data Layer for message.
using CodeSlice.Business.Interface;
using CodeSlice.Data.Interface;
using CodeSlice.Data;
namespace CodeSlice.Business
{
    public class Dummy : IDummy
    {
        private IDataDummy _data;

        public Dummy(IDataDummy data)
        {
            _data = data;
        }
        public string GetMessage()
        {
            var result = data.GetMessage();
            // Your business logic here
            return result ;
        }
    }
}

Data Layer

C#
//Data Interface
namespace CodeSlice.Data.Interface
{
    public interface IDummyData
    {
        string GetMessage();
    }
}
C#
//Data Layer or Repository Service to get data. 
using CodeSlice.Data.Interface; 
namespace CodeSlice.Data 
{ 
    public string GetMessage() 
    { 
        // your code to fetch data here; 
        return "From DB"; 
    } 
}

Extending Unity Container

Create custom dependency extension class extending UnityContainerExtension in middle layer. Override Initialize Method and Register Data Layer dependencies.

C#
using CodeSlice.Data;
using CodeSlice.Data.Interface;
using Microsoft.Practices.Unity;
namespace CodeSlice.Business
{
    public class DependencyInjectionExtension : UnityContainerExtension
    {
        protected override void Initialize()
        {
            Container.RegisterType<IDataDummy, DataDummy>();
        }
    }
}

Add new extension to your unity container defined in RegisterType() method of UnityConfig class.

C#
public static void RegisterTypes(IUnityContainer container)
{          
      // Register your middle layer types here
      container.RegisterType<IDummy, Dummy>();
      //Data Layer dependency mapping as extension 
      container.AddNewExtension<DependencyInjectionExtension>();
}

Please let me know your feedback or if you think if there is any other option to get this done without separating mapping out of the web project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Cognizant
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to register new extensions in 4-5 layered architecture Pin
shakoor hussain16-Nov-19 17:56
shakoor hussain16-Nov-19 17:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.