Wednesday, February 2, 2011

Getting Ninject to work with MVC 3

Before getting started lets make sure everyone is on the same page.  The screenshots and descriptions below assume the use of the following products and tools.

  • Visual Studio 2010
  • ASP.NET MVC 3
  • .NET 4.0 framework

Lets start by creating a new ASP.NET MVC 3 Web Application

image

Lets go ahead and choose the Empty template.  We can bypass using a Test Project at this time.

image

Once the solution is created lets add the following folder structure:

image

Inside the service folder lets add an interface for a messaging service called IMessagingService.  We will be using the messaging service in our home controller that we will be creating in the next couple of steps.  Here is the code that should be in the messaging service interface.

namespace NinjectExample.Infrastructure.Service
{
    public interface IMessagingService
    {
        string HellowWorldMessage();
    }
}

Now lets create the actual messaging service class also in the service folder.  Here is the code that should be in the messaging service class.

namespace NinjectExample.Infrastructure.Service
{
    public class MessagingService : IMessagingService
    {
        public string HellowWorldMessage()
        {
            return "Hello World";
        }
    }
}

Your folder and file structure should look something like this.

image

Now lets go ahead and add a HomeController to the Controllers folder.  Here is the code for the first Home Controller.

using System.Web.Mvc;
using NinjectExample.Infrastructure.Service;

namespace NinjectExample.Controllers
{
    public class HomeController : Controller
    {
        public IMessagingService MessagingService { get; private set; }


        public HomeController(IMessagingService messagingService)
        {
            MessagingService = messagingService;
        }

        public ContentResult Index()
        {
            return new ContentResult(){Content = MessagingService.HellowWorldMessage()};
        }

    }
}

Now before we can actually run our application we need to install Ninject.  Lets do this by right clicking the project in the Solution Explorer and selecting “Add Library Package Reference”.  You should see a window that looks like this.

image

  1. Click the “Online” item in the accordion.
  2. Search fro “ninject”.
  3. Click the install button next to Ninject.MVC3.
  4. After a few moments the install button will go away and a green check mark will be displayed.  Go ahead and close the window.

You should now see two new references added to your project.  One for Ninject and the other for Ninject.MVC3.  You should also see a file called “AppStart_NinjectMVC3.cs” added to the root of your folder.  Modify the “AppStart_NinjectMVC3.cs” file to look like this.

using System.Web.Mvc;
using Ninject;
using Ninject.Mvc3;
using NinjectExample.Infrastructure.Service;

[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectExample.AppStart_NinjectMVC3), "Start")]

namespace NinjectExample {
    public static class AppStart_NinjectMVC3 {
        public static void RegisterServices(IKernel kernel) {
            //kernel.Bind<IThingRepository>().To<SqlThingRepository>();
            kernel.Bind<IMessagingService>().To<MessagingService>();
        }

        public static void Start() {
            // Create Ninject DI Kernel
            IKernel kernel = new StandardKernel();

            // Register services with our Ninject DI Container
            RegisterServices(kernel);

            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
        }
    }
}

Note that in the RegisterServices method I added a new kernel.Bind line that tells the application that anytime I see a IMessagingService reference, new up and send in a MessagingService.

There are no other modifications needed.  If you run the application the Home\Index route should return the text “Hello World” in the browser window.

1 comment:

  1. After following these steps, I now receive an error when adding a new Controller ("Controller with read/write actions and views, using Entity Framework").

    I now receive the error:
    Could not load file or assembly '....\Ninject.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)

    However, Ninject is working perfectly.

    Can you advise whether you receive this same error?

    ReplyDelete