DEV Community

Cover image for Integrate Ninject into ASP.NET MVC 5 and Web API.
1001binary
1001binary

Posted on

Integrate Ninject into ASP.NET MVC 5 and Web API.

In this post, I show you how to integrate Ninject into ASP.NET MVC and Web API.

Prior to the implementation, I explain to you what Ninject is. Ninject is a IoC framework for .NET platform to help you to integrate DI into .NET applications easily.

Install Nuget Packages

  • Ninject.Web.WebApi
  • Ninject.MVC5

Implement the integration

Integrating Ninject is simple:

  • Global.asax must inherit NinjectHttpApplication
  • Override the CreateKernel method.
  • Inject required services.
Public Class Global_asax
    Inherits NinjectHttpApplication

    Protected Overrides Function CreateKernel() As IKernel
        Dim kernel = New StandardKernel()
        RegisterServices(kernel)
        Return kernel
    End Function

    Private Sub RegisterServices(ByVal kernel As IKernel)
        ' TODO: inject your services here...
        ' e.g. kernel.Bind(Of IUserAccountRepository)().To(Of UserAccountRepository).InRequestScope()
    End Sub

    Protected Overrides Sub OnApplicationStarted()
        MyBase.OnApplicationStarted()
        AreaRegistration.RegisterAllAreas()
        GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
        RouteConfig.RegisterRoutes(RouteTable.Routes)
    End Sub

End Class
Enter fullscreen mode Exit fullscreen mode

ASP.NET MVC

Public Class HomeController
    Inherits Controller

    Private ReadOnly UserRepository As IUserAccountRepository

    Public Sub New(UserRepository As IUserAccountRepository)
        Me.UserRepository = UserRepository
    End Sub

End Class
Enter fullscreen mode Exit fullscreen mode

ASP.NET Web API

Public Class UserApiController
    Inherits ApiController

    Private ReadOnly UserRepository As IUserAccountRepository

    Public Sub New(UserRepository As IUserAccountRepository)
        Me.UserRepository = UserRepository
    End Sub

End Class
Enter fullscreen mode Exit fullscreen mode

Hope you enjoy this post

Happy coding :)

Top comments (0)