2016-04-29 35 views
0

寻找对此的答案(或替代方案)。静态方法中的自动解析分辨率

我正在重构我们的一个核心应用程序来使用一些DI。选择的武器是Autofac。

一切已经持续膨胀,直到我偶然发现了这个扩展方法:

public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName) 
    { 


     IRouteService _routeService; //<---------How do I get the instance here? 


     Models.Routing.Routes thisRoute = _routeService.GetRoutes().FirstOrDefault(x => x.Action == actionName && x.Controller == controllerName); 

     ///removed for brevity.... 

     return false; 
    } 

此扩展用于保护应用程序的部分(显示的链接,隐藏的链接,等等)。

幸运的是扩展只用于一个视图(_shared) - 但它是一个布局视图 - 所以它碰到了一切。

我正在考虑重构签名注入List<Routes>这样的:

public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName, List<Routes> routes) 

这将使这个简单:

Models.Routing.Routes thisRoute = routes.FirstOrDefault(x => x.Action == actionName && x.Controller == controllerName); 

但是就像我说这是一个部分(_shared)视图。

我需要修改每个ViewModel以包含签名中的路由......我真的不想这样做。

根本问题是DI和静态类是不好的ju ju ....我明白了。然而,扩展方法是.NET开发的一部分(也是一个强大的功能)。假定在自定义扩展方法中需要业务逻辑组件(服务),这并不遥远。

对此的任何想法?

回答

3

如果您遇到静态问题,答案是“服务位置”。这不是很漂亮,但它就是这样。

它看起来像你使用MVC,这将意味着使用DependencyResolver.Current.GetService()

+0

这变成了一个更大的事情,我的开发者之间进行了大量的技术辩论。这很有趣,它揭示了我们一直在使用的更大的惯例。但是我感谢@Travis的答案。我能够在别处使用它。 – JDBennett