asp.net-mvcdependency-injectionurlhelperrequestcontext

How do I Access the RequestContext Outside the Controller?


Background

I am trying to move business logic out from the controllers into their own services.

Controller

public class AccountController : Controller
{
    private readonly IAccountService _accountService; 

    public AccountController(IAccountService accountService)
    {
        _accountService = accountService;
    }

    ....
}

I'm using Unity to inject dependencies. I'd like to use the Url.GenerateUrl() helper method within the implementation of IAccountService but Url is a property against the controller.

I looked at the MVC source to see how this is done but it requires me to access the RequestContext from outside of the controller, and I don't know how to do that.

Question

How do I access the RequestContext from outside the controller? If that won't solve my problem, how do I solve the problem given my setup?


Solution

  • However i'd like to use the Url.GenerateUrl helper methods within my implementation of IAccountService

    Simply pass this information as parameter. Example:

    public ActionResult Index()
    {
        var someUrl = Url.Action("about");
        _accountService.Foo(someUrl);
    }
    

    Now you no longer need UrlHelper inside your service classes. Everything that needs interacting with MVC infrastructure shouldn't be placed in your service classes. They shouldn't depend on any Request, Response, Session, ... It's the controller's responsibility to work with those objects and glue them together with your service classes.