开发者

ASP.Net MVC 3 - instantiate data context class in BaseController

开发者 https://www.devze.com 2023-03-28 23:45 出处:网络
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:

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.C开发者_运维技巧ontrollers
{ 
    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
    {
    ...
    }
}


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消