views:

94

answers:

3

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)?

+1  A: 

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.

David M
+2  A: 

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...

Mauricio Scheffer
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?
zaph0d
+1  A: 

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.

Krzysztof Koźmic

related questions