Dependency injection inside the FilterAttribute attribute in ASP.NET MVC 6

I am struggling with ASP.NET MVC 6 (beta 4 release) trying to inject a service into a controller filter attribute of type AuthorizationFilterAttribute .

This is a service (it has another service)

 public class UsersTableRepository { private readonly NeurosgarContext _dbContext; public UsersTableRepository(NeurosgarContext DbContext) { _dbContext = DbContext; } public ICollection<User> AllUsers { get { return _dbContext.Users.ToList(); } } //other stuff... } 

This is the ConfigureServices method in the Startup class for services that include

  public void ConfigureServices(IServiceCollection services) { //... services.AddSingleton<NeurosgarContext>(a => NeurosgarContextFactory.GetContext()); services.AddSingleton<UifTableRepository<Nazione>>(); services.AddSingleton<UsersTableRepository>(); } 

A simple "dummy" controller with two filters defined on it. You may notice that I already made a DI inside this controller by decorating the [FromServices] property and it works.

 [Route("[controller]")] [BasicAuthenticationFilter(Order = 0)] [BasicAuthorizationFilter("Admin", Order = 1)] public class DummyController : Controller { [FromServices] public UsersTableRepository UsersRepository { get; set; } // GET: /<controller>/ [Route("[action]")] public IActionResult Index() { return View(); } } 

Executing the same DI inside BasicAuthenticationFilter does not work, and at runtime the UserRepository property is an empty reference.

 public class BasicAuthenticationFilterAttribute : AuthorizationFilterAttribute { [FromServices] public UsersTableRepository UsersRepository { get; set; } public override void OnAuthorization(AuthorizationContext filterContext) { if (!Authenticate(filterContext.HttpContext)) { // 401 Response var result = new HttpUnauthorizedResult(); // Add the header for Basic authentication require filterContext.HttpContext.Response.Headers.Append("WWW-Authenticate", "Basic"); filterContext.Result = result; //if (!HasAllowAnonymous(context)) //{ // base.Fail(context); //} } } // ... } 

Any idea on how to solve this problem?

+6
source share
1 answer

Refrain from injecting dependencies into your attributes as described here . Make the attribute passive or make your attribute a modest object as described here .

+7
source

Source: https://habr.com/ru/post/986724/


All Articles