How to inject UrlHelper in MVC using Castle Windsor
Asked Answered
H

3

6

I have a component that has a dependency on UrlHelper that I need to register using Castle Windsor. UrlHelper in turn has depdendencies on RequestContext (and RouteCollection).

Now my controller has a Url property of type UrlHelper but cannot really access this as far as I can tell.

What is the most efficient way to register my UrlHelper dependency (using fluent configuration)?

Hindustani answered 2/6, 2010 at 13:47 Comment(0)
H
7

Not pretty and not tested but it should work:

container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<UrlHelper>()
    .LifeStyle.PerWebRequest
    .UsingFactoryMethod(() => {
        var context = new HttpContextWrapper(HttpContext.Current);
        var routeData = RouteTable.Routes.GetRouteData(context);
        return new UrlHelper(new RequestContext(context, routeData));
    }));

Future releases of Windsor won't need the FactorySupportFacility to use UsingFactoryMethod.

Anyway it seems rather odd to have a dependency to UrlHelper...

Hannah answered 2/6, 2010 at 19:22 Comment(2)
Thanks, that is pretty much what I ended up with. I am using UrlHelper in an OutputCacheHelper class that removes pages from the cache using for example: _response.RemoveOutputCacheItem(_urlHelper.RouteUrl("Home")); This is used by multiple controllers, so it seemed to make sense to refactor it into a separate class which has dependencies on HttpRequestBase and UrlHelper. Is this bad?Hindustani
@Mauricio Scheffer: Why does it seem odd? How are you supposed to generate URLs in services? Say you need to stick a URL into an e-mail within an e-mail sending service? How would you do that?Charlena
M
3

I blogged about it (among other things) few days ago here. It works with (upcoming) Windsor 2.5. Until that, Mauricio's suggestion should be your safest bet.

Meredi answered 2/6, 2010 at 23:21 Comment(0)
A
1

The only way I've found to do this is to declare an IUrlHelper interface, and to implement a wrapper class around UrlHelper that implements it. Then we can either inject an instance of the wrapper class using IOC, or in unit tests inject a mock object. It's a bit of a pain, but it works.

Altocumulus answered 2/6, 2010 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.