tags:

views:

66

answers:

4
+3  Q: 

MVC Model State

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 ModelValidation(this.ModelState));
}
public New(IProjectService service)
{
_service = service;
}

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

A: 

Controller base class?

Arnis L.
+1  A: 

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()
     {
     }
 }
mlsteeves
+4  A: 

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.

David M
Sunny
@Sunny - different schools of thought on this. I understand the argument to use constructor injection for necessary dependencies, but there's also an argument to use a consistent injection approach, and of course not all IOC containers support all methods as easily as others. But this is the sort of thing the OP will pick up on when reading around the subject hopefully.
David M
+2  A: 

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.

Matthew Vines
Yes, anytime that you are copy/pasting a lot of code, there is usually a better way! :)
mlsteeves