Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject UrlHelper in MVC using Castle Windsor

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

like image 580
Paul Hiles Avatar asked Jun 02 '10 13:06

Paul Hiles


3 Answers

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

like image 156
Mauricio Scheffer Avatar answered Nov 09 '22 01:11

Mauricio Scheffer


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.

like image 3
Krzysztof Kozmic Avatar answered Nov 09 '22 03:11

Krzysztof Kozmic


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.

like image 1
David M Avatar answered Nov 09 '22 01:11

David M