Making the MVC3 Model independent of data source (using Ninject) [beginners]

Here are three “rules” I try to adopt to in my relearning MVC3 app:

  • The Views should not do anything else than display the data.
  • The Controllers should (on get’s) only be responsible for serving the right viewmodel to the right view for the particular request.
  • The Models should not depend on one particular source of data.

In my last post I made a small controller that constructed a mock viewmodel and sent it to the View. Now I like to use a separate mock data class to serve that purpose. The controller should take the id from the Url, get the data from the data class and serve it to the view.

Other than that I like to be able to change from my mock data to a real database, back and forth. I accomplish that with the help of an interface for the datacontext and the use of a dependency injection framework for the actual coupling. I am new to DI and use Ninject (install-package Ninject) as I heard it’s easy to use.

using System;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;

namespace MyApplication
{
    public interface IDataLayer
    {
        dynamic GetItem(int id);
        dynamic SaveItem(dynamic item);
    }

    public class MockDataLayer : IDataLayer
    {
        public dynamic GetItem(int id)
        {
            dynamic item = new System.Dynamic.ExpandoObject();
            item.Id = id;
            item.Name = "Some name";
            return item;
        }
        public dynamic SaveItem(dynamic item)
        {
            return item;
        }
    }
    public class ItemController : Controller
    {
        public ActionResult Display(int id = 0)
        {
            dynamic viewModel = MvcApplication.DataContext.GetItem(id);
            return View(viewModel);
        }
    }
    public class MvcApplication : System.Web.HttpApplication
    {
        public static IDataLayer DataContext;

        protected void Application_Start(object sender, EventArgs e)
        {
            // the following three rows is the Ninject use
            IKernel kernel = new StandardKernel();

            kernel.Bind<IDataLayer>().To<MockDataLayer>();
            DataContext = kernel.Get<IDataLayer>();

            RouteTable.Routes.MapRoute("", "{id}", new { controller = "Item", action = "Display", id = UrlParameter.Optional });
        }
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s