在ASP.NET vNext过滤器中获取注入的对象

Son*_*Sam 6 asp.net-core

我正在尝试创建自定义authorize属性,但在使用默认依赖注入框架的asp.net vnext中,我不知道如何获取注入的对象.我需要在默认的ctor中获取注入的对象.

   public  class CustomAttribute
{

   private IDb _db;

   public CustomAttribute()
   {
       _db = null; // get injected object
   }

   public CustomAttribute(IDb db)
   {
       _db = db;
   }

   // apply all authentication logic
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*lla 9

您可以使用ServiceFilterAttribute来实现此目的.服务过滤器属性允许DI系统负责实例化和维护过滤器CustomAuthorizeFilter及其任何所需服务的生命周期.

例:

// register with DI
services.AddScoped<ApplicationDbContext>();
services.AddTransient<CustomAuthorizeFilter>();

//------------------

public class CustomAuthorizeFilter : IAsyncAuthorizationFilter
{
    private readonly ApplicationDbContext _db;

    public CustomAuthorizeFilter(ApplicationDbContext db)
    {
        _db = db;
    }

    public Task OnAuthorizationAsync(AuthorizationContext context)
    {
        //do something here    
    }
}

//------------------

[ServiceFilter(typeof(CustomAuthorizeFilter))]
public class AdminController : Controller
{
    // do something here
}
Run Code Online (Sandbox Code Playgroud)

  • @Son_of_Sam:当然,它也可能是一个瞬态......它只取决于你正在实施的场景...... (2认同)