Wednesday 1 November 2023

How to implemnet Dependency Injection in ASP.NET MVC 4? Explain with example.

Dependency Injection (DI) is a software design pattern that promotes loosely coupled code by allowing dependencies to be injected into a class from the outside, rather than being created or managed within the class. In ASP.NET MVC 4, you can implement DI using various DI containers such as Unity, Ninject, or Simple Injector. Here, I'll provide an example using Unity for dependency injection.

 

Step 1: Create an ASP.NET MVC 4 Project If you haven't already, create a new ASP.NET MVC 4 project in Visual Studio.

 

Step 2: Install Unity Container You need to install the Unity NuGet package to your project. Open the Package Manager Console and run:

-----------------------------------------------------------------------------------------------------------------------------

Install-Package Unity.Mvc4

-----------------------------------------------------------------------------------------------------------------------------

Step 3: Create a Dependency Let's assume you have a service that you want to inject into your controller. First, create an interface and a class for this service:

-----------------------------------------------------------------------------------------------------------------------------

// IService.cs

public interface IService

{

    string GetData();

}


// Service.cs

public class Service : IService

{

    public string GetData()

    {

        return "Hello from Service!";

    }

}

Step 4: Configure Dependency Injection In your Global.asax.cs file, configure Unity to manage the dependencies. Add the following code to the Application_Start method:

-----------------------------------------------------------------------------------------------------------------------------

protected void Application_Start()

{

    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);


    // Configure Unity Container

    var container = new UnityContainer();

    container.RegisterType<IService, Service>();


    // Set the Unity DependencyResolver

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

}

This code sets up the Unity container and tells it that when someone asks for an IService, it should provide an instance of the Service class.

Step 5: Inject the Dependency Now, you can inject the dependency into your controller. Here's an example:

-----------------------------------------------------------------------------------------------------------------------------

public class HomeController : Controller

{

    private readonly IService _service;


    // Constructor injection

    public HomeController(IService service)

    {

        _service = service;

    }


    public ActionResult Index()

    {

        string data = _service.GetData();

        return View(data);

    }

}

By using constructor injection, the IService is automatically injected when an instance of HomeController is created.

Step 6: Use the Dependency in a View In your view (Index.cshtml), you can display the data from the injected service:

-----------------------------------------------------------------------------------------------------------------------------

@model string


<!DOCTYPE html>

<html>

<head>

    <title>Dependency Injection Example</title>

</head>

<body>

    <h1>@Model</h1>

</body>

</html>

When you run the application, the text from the Service will be displayed on the Index page.

This is a basic example of implementing Dependency Injection in ASP.NET MVC 4 using the Unity container. It promotes better separation of concerns and testability by allowing you to easily switch out dependencies and mock them during unit testing.