gpt4 book ai didi

dependency-injection - 在 dotnetcore DI 世界中与助手一起工作

转载 作者:行者123 更新时间:2023-12-04 16:47:02 25 4
gpt4 key购买 nike

我喜欢在我的应用程序中使用静态帮助器类来处理常见的管道问题,例如检查角色或 Razor Html 帮助器和其他东西……但是在 DI 世界中如何做到这一点?

比如说我想要一个扩展助手来检查用户是否是管理员

public static async Task<bool> IsAdmin(this ApplicationUser user)
...
if(user.IsAdmin()){...}

所以预核心我可以忽略 DI 并在 IsAdmin 中创建一个 UserManager 做我需要做的任何事情。但是现在有没有办法让这些助手中的 UserManager 直接使用?我能看到的唯一方法是将它注入(inject) Controller ,然后传递到方法中(我觉得很难看)。然后是尝试在 Razor View 中执行 user.IsAdmin() 的问题,我是否需要将 UserManager 添加到 ViewData 集合以将其放入 View 标记中?

我是不是漏掉了什么?

谢谢,史蒂夫

最佳答案

首先,如果您只是问如何将静态类与 di 一起使用,我会说您的问题与 How to use DI inside a static Method in Asp.net Core rc1 重复

但是据我所知,您还有其他问题吗?

But now is there no way to get the UserManager in these helpers to just use?

是的,有办法:Service Locator图案。但它是一个反模式(see this article) .您应尽可能避免使用此模式。另见 discussion在 github 上。

The only way I can see is to inject it into the Controller, then pass along into the method (which I find ugly)

我认为这种方式比你想要的要好。我更喜欢这个。

Then there's the issue of trying to do user.IsAdmin() in the Razor view, would I need to add the UserManager to the ViewData collection to get it into the view markup?

在 Aspnet Core 中,您可以将依赖项注入(inject) View ,因此您无需使用 ViewData。您只需将 UserManager 注入(inject)到您的 View 中,然后将其作为参数传递给方法。看看official docs

关于dependency-injection - 在 dotnetcore DI 世界中与助手一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com