How to Implement the dependency injection in asp.net MVC ?


what is the dependency injection ?

Dependency Injection is a software design pattern that allow us to develop loosely coupled application.

What is the Inversion of Control (IoC) ?

Inversion of Control (IoC) refers to a programming style where a framework controls the program flow with the help of Dependency Injection.

How to Implement the Dependency Injection in Asp.net MVC application ?

We can implement the dependency injection in the following ways

Step 1: Create the MVC application.
Step 2: Go to Solution explorer and click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

Step 3: Create the Service folder in asp.net MVC application and write some simple service using interface like this

namespace Dependency_Injection_Sample.Service
{
    /// <summary>
    /// Defines the <see cref="ICompanyService" />
    /// </summary>
    public interface ICompanyService
    {
        /// <summary>
        /// This is the interface
        /// </summary>
        /// <returns>string</returns>
        string getCompany();
    }
}

Step 4: Create the CompanyService class using interface like this

namespace Dependency_Injection_Sample.Service
{
    /// <summary>
    /// This is the CompanyService class
    /// </summary>
    public class CompanyService : ICompanyService
    {
        /// <summary>
        /// Defines the Name
        /// </summary>
        private const string Name = "Chandradev Software Pvt Ltd.";

        /// <summary>
        /// This will return the company Name
        /// </summary>
        /// <returns>string</returns>
        public string getCompany()
        {
            return Name;
        }
    }
}


Step 5: Go to the UnityConfig file and register the components like this

Step 6: Now go to the home controller and create the dependency injection using private constructor like this

Step 7: In index page, you call the Viewbag like this

@ViewBag.CompanyName

Step 7: Now run the application, you will see the output like this