我正在尝试创建自定义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
}
答案 0 :(得分: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
}