2016-04-29 27 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