Dependency Injection Framework (Ninject) and .NET

From the previous lesson you can check our progress with the Dependency Injection pattern:
We talked about the week dependency between the classes but we didn’t give an example with an DI container.

Basically a DI container is a container which knows which class is the realization of a given interface. So if a controller says: “Hello, i want IAccountService relization”, the container checks which is the realization (which in current situation is AccountService class), creates a reference to the class and passes it to the controller. The controller can only use the methods declared in the interface.

Such a nice example is Ninject. Website. You can also install it through NuGet, as I am doing.

What is the idea of Ninject ?
The idea is that you declare the connection between an interface and a class in a single place and from there on when someone wants the realization of an interface, Ninject will give the realization for you.

So where is the place in which we declare the connection between a class and an interface?

During the installation Ninject has created in the project folder called AppStart a class called NinjectWebCommon. Inside we have a method called RegisterServices, in which we can register the connection between Interfaces and Classes. Here is how my methods looks like:

 private static void RegisterServices(IKernel kernel)
        {
            
    kernel.Bind<IAuthenticationService>().To<ApiAuthenticationService>().WhenInjectedInto(typeof(ApiController)).InRequestScope();

    kernel.Bind<IAuthenticationService>().To<ApiAuthenticationService>().WhenInjectedInto(typeof(ApiAccountService)).InRequestScope();

    kernel.Bind<IAccountService>().To<ApiAccountService>().When(ctx =>
    HttpContext.Current.Request.Url.AbsolutePath.StartsWith("/api/")).InRequestScope();

    kernel.Bind<IAccountService>().To<AccountService>().When(ctx =>
    !HttpContext.Current.Request.Url.AbsolutePath.StartsWith("/api/")).InRequestScope();

    kernel.BindFilter<WebAllowOnlyAnonymousFilter>(System.Web.Mvc.FilterScope.Controller,
    0).WhenControllerHas<WebAllowOnlyAnonymousAttribute>().InRequestScope();

    kernel.BindHttpFilter<ApiAuthorizeFilter>(System.Web.Http.Filters.FilterScope.Controller).WhenControllerHas<ApiAuthorizeAttribute>().InRequestScope()

    .WithConstructorArgumentFromControllerAttribute<ApiAuthorizeAttribute>("_roles", attribute => attribute.Roles);

}

You can also make complicated declarations here like the declaration for IAccountService when it is used in Web API.

You can just say: Bind<>().To<>() and to strop without adding any conditions. I add the method InRequestScope so the dependencies are applicable only for the current request and will not be store after the request expires.

You don’t have to do anything exceptional to get the realization of a given class. All you can do is just request the required class interface in the constructor of your current class – that is called constructor injection. Ninject will populate the realization in the constructor for me. You can debug and you will see tha accountService is a real object with methods from the AccountService class. You can also easily debug the methods in your realization class.

I also have attributes which you can see at last place. They limit the user access on some pages like user access for anonymous users or for users with role admin.

A good example for usage of Ninject with ASP.NET MVC4 can be seen Here.

If you stay with me on the next few articles we will make a sample project of ASP.NET MVC 4 with Ninject.

Lessons history:

  1. Dependency Injection
  2. Current

You may also like...