【问题标题】:how to inject dependency in _viewimports file如何在 _viewimports 文件中注入依赖项
【发布时间】:2017-08-16 12:42:30
【问题描述】:

我正在尝试在 asp.net Core 中生成一个通用的 BaseViewPage 来访问当前用户的身份。

为此,我创建了一个 BaseViewPage.cs 文件 -

 public abstract class BaseViewPage<TModel> : RazorPage<TModel>
    {
        private static ClaimsPrincipal principal;
        public BaseViewPage(IPrincipal _principal)
        {
            principal = _principal as ClaimsPrincipal;
        }
    }

正如您在此处的构造函数中看到的那样,我正在注入 IPrincipal 类型的依赖项,以便在运行时对其进行定义。

现在是时候在 _viewimports.cshtml 文件中继承它,以便在所有视图页面中使用当前用户,如下所示 -

@using TWCStore
@inherits MyStore.Helpers.BaseViewPage<TModel>
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

每当我尝试在我的视图中使用任何属性时 - ProductCategories.cshtml 都会在此处调用错误

严重性代码描述项目文件行抑制状态 错误 CS7036 没有给出对应于 所需的形式参数“_principal” 'BaseViewPage.BaseViewPage(IPrincipal)' MyStore D:\Projects\TWCStore\TWCStore\Views\Store\ProductCategories.cshtml 1 活动

我假设当我注入依赖项时,它希望我也将IPrincipal 作为依赖项放在这里 -

 @inherits MyStore.Helpers.BaseViewPage<TModel>

如何在此处注入此依赖项?

【问题讨论】:

  • 你试过在startup.cs中注册吗?
  • ClaimsPrincipal 不是使用依赖注入注册的东西,身份验证中间件会根据每个请求的身份验证 cookie 创建主体。您不需要注入它,因为它已经在视图中可用。用户属性在视图中本质上是可用的,并且是 ClaimsPrincipal
  • 也可能最好不要创建具有构造函数依赖项的基本页面,因为您可以在视图内使用@inject 来注入东西
  • _viewimports 只是为了让命名空间和 taghelper 在其他视图中全局可用,仅此而已,你不应该尝试在那里做其他事情
  • @JoeAudette,在所有情况下,如果我不注入 ClaimsPrincipal,我都会得到 null。让我知道您如何在不注射的情况下获得索赔?另外,我的问题是通过注入接口而不是继承来解决的。我应该在空闲时间更新问题。

标签: asp.net asp.net-mvc asp.net-core asp.net-identity


【解决方案1】:

我在这里写这个问题的解决方案(实际上是替代方案)已经很晚了。

所以我遵循了依赖注入(抱歉现在忘记了帮助链接)。

这就是我所做的 -

创建界面

public interface IAppUserAccessor
    {
        int MemberId { get; }
    }

解析器类

 public class AppUserAccessor : IAppUserAccessor
    {
        private readonly MyContext _context;
        public AppUserAccessor(MyContext context)
        {
            _context = context;
        }

        int IAppUserAccessor.MemberId
        {
            get
            {
                return _context.Member.MemberId;
            }
        }
    }

在 StartUp.cs 的“ConfigureServices”部分下注册服务

 services.AddTransient<IAppUserAccessor, AppUserAccessor>();

注入 _viewimports.cshtml

@using MyApplication
@inject MyApplication.Helpers.IAppUserAccessor AppUserAccessor

现在这在每个视图中都可以访问 -

@AppUserAccessor.MemberId

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2017-08-06
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多