0

When adding a controller in ASP.Net MVC 3 using "Controller with Read/Write actions and views, using EntityFramework" as template, it generates a class as follows:

namespace Project.Controllers
{ 
    public class Default1Controller : Controller
    {
        private ProjectEntities db = new ProjectEntities();

        ...
    }
}

Now, I would like to know if it would be a good practice to change this so that my Controller would inherit a custom base controller that would instantiate ProjectEntities. It would look as follows:

BaseController:

namespace MatchesHorsConcours.Controllers
{
    public class BaseController : Controller
    {
        protected MatchesEntities db = new MatchesEntities();
        ...
    }
}

Other controllers:

namespace Project.Controllers
{ 
    public class Default1Controller : BaseController
    {
    ...
    }
}
Jean-François Beauchamp
  • 5,485
  • 8
  • 43
  • 77
  • 1
    It's better practice to use Dependency Injection. There are a number of libraries out there to do this. To name a few, Ninject, Castle Windsor or Autofac – David Fox Aug 17 '11 at 17:11

2 Answers2

2

This technique is useful when you need logic in your master page (for example, to dynamically render menu options). Read about this here: http://www.asp.net/mvc/tutorials/passing-data-to-view-master-pages-cs

However, in general this is not a good technique. I would recommend using dependency injection (Ninject works well with MVC and is easy to implement)

Steven Striga
  • 1,371
  • 2
  • 10
  • 17
1

No absolutely not. It makes totally untestable. Please use repository pattern and constructor injection if possible: Repository Pattern vs DAL

Community
  • 1
  • 1
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240