【问题标题】:Autofac Resolution in Static Method静态方法中的 Autofac 分辨率
【发布时间】:2016-04-29 22:37:19
【问题描述】:

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

我正在重构我们的一个核心应用程序以使用一些 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&lt;Routes&gt;,如下所示:

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

对此有什么想法吗?

【问题讨论】:

    标签: extension-methods autofac static-methods


    【解决方案1】:

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

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

    【讨论】:

    • 这变成了更大的事情,我的开发人员之间进行了很多技术辩论。有趣的是,这发现了我们一直在使用的更大的约定。但我感谢@Travis 的回答。我可以在其他地方使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多