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
    {
    ...
    }
}
1
  • 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 Commented Aug 17, 2011 at 17:11

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.