Skip to main content

Dependency Injection And ApiController - Web API

If you are a beginner level then the first question will come to your mind, 'What is Dependency Injection?'.
Dependency Injection demonstrates how to create loosely coupled classes.
Dependency Injection is one of the ways to implement 'Inversion Of Control' principle.
now next question raise in your mind what is 'Inversion Of Control' principle?
Inversion of control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.

Typically Dependency Injection (DI) involves four roles
- Service
- Client
- Interface
- Injector

Any object of the class that coming in request cycle can be considered as Service.
Service class object created by depending class can be considered as Client.
Client object communication with Service object can be defined with Interface.
Using Injector, Service object created and injecting into the Client.

There are 3 ways you can implement DI
  1. Constructor injection
  2. Method injection
  3. Property injection
Constructor Injection
In this way, the service object created in client constructor using the parameter.
e.g:
private IService service;
public Client(IService service)
{
    this.service = service;
}

By refer above code snippets, a question may come to your mind where or how an object of service class created.
This we can do by using Inversion of Control containers. There are many IoC container available like Unity, Autofac etc.

Below I am defining how you can use Autofac IoC container in your web api project.

In your web api project run the below command in Package Manager Console.
- Install-Package Autofac.WebApi2

this will download and refer the required dll reference in the current project.
Now in the Application_Start method of Global.asax.cs file, add the below lines for IoC container.

var builder = new ContainerBuilder();
// Get your HttpConfiguration.
var config = GlobalConfiguration.Configuration;
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// OPTIONAL: Register the Autofac filter provider.
builder.RegisterWebApiFilterProvider(config);
// This will register the required service class object in above snippets.
builder.RegisterType<Service>().As<IService>();
// Set the dependency resolver to be Autofac.
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);


Below is the complete code
DIClientController.cs
using System.Web.Http;
namespace LearnOnlineAspNet.MVCexample.Controllers
{
    public interface IService
    {
        string Message();
    }
    public class Service : IService
    {
        public string Message()
        {
            return "Message from service";
        }
    }
    public class DIClientController : ApiController
    {
        private IService service;
        public DIClientController(IService service)
        {
            this.service = service;
        }
        [HttpGet]
        public string GetMessage()
        {
            return service.Message();
        }
    }
}


Global.asax.cs
using Autofac;
using Autofac.Integration.WebApi;
using LearnOnlineAspNet.MVCexample.Controllers;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace LearnOnlineAspNet.MVCexample
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            var builder = new ContainerBuilder();
            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;
            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);
            builder.RegisterType<Service>().As<IService>();
            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
    }
}

Hope it helps you to understand and how to implement Dependency Injection in Controller.