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()
{
}
}
精彩评论