Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Model State

Tags:

asp.net-mvc

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?

like image 579
gnome Avatar asked Jan 22 '23 09:01

gnome


2 Answers

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.

like image 116
David M Avatar answered Feb 01 '23 10:02

David M


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.

like image 33
Matthew Vines Avatar answered Feb 01 '23 12:02

Matthew Vines