简体   繁体   中英

Dependency injection in custom attribute

I have a custom attribute that gets 2 parameters, how can I inject this parameters to 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();
}

Firstly,you need inject IHttpContextAccessor instead of HttpContextAccessor .

Secondly,service is not a valid attribute parameter type.I suggest that you could use ActionFilterAttribute or any other Attribute (It depends on your detailed scenario) which could cast to ServiceFilterAttribute or TypeFilterAttribute .

Here is a whole working demo:

Custom 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();
}

Register services:

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

Reference:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM