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)?
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...
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.
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.
上一篇: MVC 2.0和地区温莎城堡