如何使用Castle Windsor在MVC中注入UrlHelper

Pau*_*les 6 castle-windsor asp.net-mvc-2

我有一个依赖于UrlHelper的组件,我需要使用Castle Windsor注册.UrlHelper反过来又对RequestContext(和RouteCollection)有所了解.

现在我的控制器有一个类型为UrlHelper的Url属性,但据我所知,它无法真正访问它.

注册我的UrlHelper依赖项的最有效方法是什么(使用流畅的配置)?

Mau*_*fer 7

不漂亮,没有测试,但它应该工作:

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));
    }));
Run Code Online (Sandbox Code Playgroud)

Windsor的未来版本不需要FactorySupportFacility来使用UsingFactoryMethod.

无论如何,对UrlHelper依赖似乎很奇怪......