开发者

MVC Model State

开发者 https://www.devze.com 2022-12-23 14:16 出处:网络
Greetings On all my controllers I recycle the same code that wraps my models and to accesses the service layer -- and I\'m tired for copy / pasting it into each controller:

Greetings On all my controllers I recycle the same code that wraps my models and to accesses the service layer -- and I'm tired for copy / pasting it into each controller:

private IProjectService _service;
public New()
{
_service = new ProjectService(new ModelValida开发者_Python百科tion(this.ModelState));
}
public New(IProjectService service)
{
_service = service;
}

Is there someplace where I can place this where all my controllers access it?


You could put in a base controller class that all your other controllers inherit from:

public class BaseController : Controller
{
    protected IProjectService Service { get; private set; }
    public New()
    {
        Service = new ProjectService(new ModelValidation(this.ModelState));
    }
    public New(IProjectService service)
    {
        Service = service;
    }
}

Alternatively, you could read up on dependency injection and look at using an IOC container to inject these dependencies.


Welcome to the wonderful world of code smells. You have found one without even knowing what it was. Whenever you think to yourself. "There has to be a better way." There is. In this case a base class would go a long way toward solving your problem.


Controller base class?


Create a base controller, and derive your controllers from it.

 public class BaseController : Controller
 { 
      protected IProjectService _service;
      public New()
      {
           _service = new ProjectService(new ModelValidation(this.ModelState));
      }
      public New(IProjectService service)
      {
           _service = service;
      }
 }
 public class MyController : BaseController
 {
     public ActionResult Index()
     {
     }
 }
0

精彩评论

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

关注公众号