gpt4 book ai didi

c# - 自定义属性中的依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-05 04:53:36 29 4
gpt4 key购买 nike

我有一个获取 2 个参数的自定义属性,如何将此参数注入(inject) MyAttribute

public class MyAttribute : Attribute
{
private readonly HttpContextAccessor _accessor;
private readonly IUserService _userService;


public MyAttribute(HttpContextAccessor accessor, IUserService userService)
{
_accessor = accessor;
_userService = userService;
// ...
}
}

Controller :

[MyAttribute()]
[Route("/action")]
public IActionResult Action()
{
retuen View();
}

最佳答案

首先,您需要注入(inject) IHttpContextAccessor 而不是 HttpContextAccessor

其次,服务不是有效的属性参数类型。我建议您可以使用ActionFilterAttribute 或任何其他Attribute(这取决于您的详细场景)可以转换到 ServiceFilterAttributeTypeFilterAttribute

这是一个完整的工作演示:

自定义 ActionFilterAttribute:

public class MyAttribute : ActionFilterAttribute
{
private readonly IHttpContextAccessor _accessor;
private readonly IUserService _userService;


public MyAttribute(IHttpContextAccessor accessor, IUserService userService)
{
_accessor = accessor;
_userService = userService;
}
}

Controller :

//[ServiceFilter(typeof(MyAttribute))]
[TypeFilter(typeof(MyAttribute))]
public async Task<IActionResult> Index()
{
return View();
}

注册服务:

public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<IUserService, UserService>();
services.AddScoped<MyAttribute>();
}

引用:

get values from class and method attribute in middleware in asp.net core

关于c# - 自定义属性中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65981258/

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