2
\$\begingroup\$

I'm trying to make an MVC3 application with an exchangeable data layer. I currently have this in a single file (Global.asax.cs) for brievity.

It seems to be working as I want but as I'm new to DI I really would appreciate comments on this code.

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 MainController : Controller
{
    public ActionResult Display(int id = 0)
    {
        dynamic viewModel = Global.DataContext.GetItem(id);
        return View(viewModel);
    }
}
public class Global : System.Web.HttpApplication
{        
    public static IDataLayer dataContext;

    protected void Application_Start(object sender, EventArgs e)
    {
        IKernel kernel = new StandardKernel();

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

        RouteTable.Routes.MapRoute("", "{id}", new { controller = "Main", action = "Display", id = UrlParameter.Optional });
    }
}
\$\endgroup\$
3
\$\begingroup\$

One tip I would give is to use the "Ninject for ASP NET MVC 3" NuGet package. Install that package into your project. After doing this, you should find a file named "NinjectMVC3.cs" located in the "App_Start" folder. In this file, look for a method named RegisterServices():

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IDataLayer>().To<MockDataLayer>().InRequestScope();
}        

This sets up a MockDataLayer to be returned for each separate web request. This ensures that MockDataLayer is disposed when the web request is completed. Now, when you want to create an instance of the data layer, use MVC's built-in DependencyResolver class:

var dataContext = DependencyResolver.Current.GetService<IDataLayer>();
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.