views:

80

answers:

2

Hi, i am trying to move my business logic out from the controllers and into their own services. I have setup my controller like so:

public class AccountController : Controller
{
    private readonly IAccountService _accountService; 

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

    ....
}

The dependencies are injected fine via Microsoft Unity. However i'd like to use the Url.GenerateUrl helper methods within my implementation of IAccountService but Url is a property against the controller. I looked at the MVC source to see how this is done but i requires me to access the request context from outside of the controller but i'm not sure how this is done.

I'd appreciate it if someone could help. Thanks

A: 

This might not be quite right because I'm unable to test it at the moment, but I think that you can do something like this:

using System.Web;
using System.Web.Mvc;

// ...

var helper = new UrlHelper(HttpContext.Current.Request.RequestContext);
string url = helper.GenerateUrl(/* ... */);

It might make more sense to pass the context from the controller to your IAccountService implementation rather than grabbing it directly from HttpContext.Current.

LukeH
As @LukeH suggests, it is much easier to pass an instance of the UrlHelper to your AccountService.
Clicktricity
This does not work as there is no RequestContext property.
nfplee
@user155899: Presumably you're using .NET 3.5 then? I think the `RequestContext` property was introduced in .NET 4.
LukeH
Yeah i didn't think that. Can't undo my down vote sorry.
nfplee
@user155899: No worries. Darin's answer is the better one anyway.
LukeH
+1  A: 

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.

Darin Dimitrov
Hi, i think this is the way to go. Thanks
nfplee