MVC Model State

Hi On all my controllers, I recycle the same code that wraps my models and accesses the service - and I'm tired of copying / pasting it into each controller:

private IProjectService _service; public New() { _service = new ProjectService(new ModelValidation(this.ModelState)); } public New(IProjectService service) { _service = service; } 

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

+4
source share
4 answers

You can enter a base controller class that inherits all other controllers:

 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 can read the dependency injection and see how to use the IOC container to inject these dependencies.

+5
source

Welcome to the wonderful world of code smells . You found it without even knowing what it is. Whenever you think about yourself. "There must be a better way." There is. In this case, the base class will greatly advance the solution to your problem.

+2
source

The main controller class?

+1
source

Create a base controller and extract 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() { } } 
+1
source

Source: https://habr.com/ru/post/1304777/


All Articles