静态方法中的Autofac分辨率

时间:2016-04-29 22:37:19

标签: extension-methods autofac static-methods

寻找答案(或替代方案)。

我正在重构我们的一个核心应用程序以使用一些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;
    }

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

幸运的是,扩展只在一个View(_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和静态类很糟糕....我明白了。但是,扩展方法是.NET开发的一部分(并且是一个强大的功能)。假设在自定义扩展方法中需要业务逻辑组件(服务)并不遥不可及。

有关于此的任何想法吗?

1 个答案:

答案 0 :(得分:4)

如果您遇到静电问题,答案就是&#34;服务地点。&#34;它并不漂亮,但它就是它。

您似乎正在使用MVC,这意味着使用DependencyResolver.Current.GetService()