Web API Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Dependency Injection (DI) in ASP.NET MVC Web API

Back to: Web API Tutorial

Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. In ASP.NET MVC Web API, DI helps manage the dependencies of controllers, services, and other classes, promoting maintainability, testability, and loose coupling.

Key Concepts of DI

  1. Service: The class that provides some functionality or data.
  2. Client: The class that depends on the service.
  3. Injector: The mechanism or framework that creates and injects services into clients.

Implementing DI in ASP.NET MVC Web API

1. Install a DI Framework

ASP.NET Core has built-in support for DI. However, in classic ASP.NET Web API, you can use third-party DI frameworks like:

  • Unity
  • Autofac
  • Ninject

2. Define Services and Interfaces

Create interfaces for your services and their concrete implementations.

// IService.cs
public interface IService
{
string GetData();
}
// Service.cs
public class Service : IService
{
public string GetData()
{
return "Hello from Service!";
}
}

3. Register Dependencies

Set up a DI container and register the dependencies.

Using Unity as an Example
  1. Install the Unity package via NuGet:

    Install-Package
    Unity Install-Package
    Unity.WebApi
  2. Configure Unity in WebApiConfig.cs.

using System.Web.Http;
using Unity;
using Unity.WebApi;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Create Unity container
var container = new UnityContainer();
// Register dependencies
container.RegisterType<Iservice,Service>();
// Set the dependency resolver
config.DependencyResolver = new UnityDependencyResolver(container);
// Other Web API configurations
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
}
} </iservice,>

4. Inject Dependencies into Controllers

Use constructor injection in your controllers.

public class MyController : ApiController
{
private readonly IService _service;
public MyController(IService service)
{ _service = service;
}
[HttpGet] [Route("api/data")]
public IHttpActionResult GetData()
{
return Ok(_service.GetData());
}
}

5. Run the Application

When the application runs, the DI container injects the Service instance into the MyController constructor automatically.


Benefits of DI

  1. Decoupling: Promotes loose coupling between classes.
  2. Testability: Makes unit testing easier by allowing mock implementations of dependencies.
  3. Maintainability: Centralized configuration of dependencies.
  4. Scalability: Easily replace implementations without changing dependent code.

By integrating DI, you can build robust and modular Web API applications.

Scroll to Top