静态方法中的 Autofac 分辨率

Autofac Resolution in Static Method

正在寻找对此的答案(或替代方案)。

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

此扩展用于保护部分应用程序(显示 link、隐藏 link 等)。

幸运的是,该扩展仅在一个视图 (_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 开发的一部分(也是一个强大的功能)。假设在自定义扩展方法中需要业务逻辑组件(服务)并不牵强。

对此有什么想法吗?

如果您受困于静态,答案是 "service location." 它并不漂亮,但就是这样。

看起来您正在使用 MVC,这意味着使用 DependencyResolver.Current.GetService()