Asp.net core 在ASP.NET vNext筛选器中获取注入对象
我试图创建自定义的authorize属性,但在使用默认依赖项注入框架的asp.net vnext中,我不知道如何获取注入的对象。我需要在默认的ctor中获取注入的对象Asp.net core 在ASP.NET vNext筛选器中获取注入对象,asp.net-core,Asp.net Core,我试图创建自定义的authorize属性,但在使用默认依赖项注入框架的asp.net vnext中,我不知道如何获取注入的对象。我需要在默认的ctor中获取注入的对象 public class CustomAttribute { private IDb _db; public CustomAttribute() { _db = null; // get injected object } public CustomAttribute(ID
public class CustomAttribute
{
private IDb _db;
public CustomAttribute()
{
_db = null; // get injected object
}
public CustomAttribute(IDb db)
{
_db = db;
}
// apply all authentication logic
}
为此,您可以使用。服务过滤器属性让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
}
//向DI注册
services.addScope();
services.AddTransient();
//------------------
公共类CustomAuthorizationFilter:IAsyncAuthorizationFilter
{
私有只读应用程序dbContext_db;
公共CustomAuthorizeFilter(ApplicationDbContext数据库)
{
_db=db;
}
AuthorizationAsync(AuthorizationContext上下文)上的公共任务
{
//在这里做点什么
}
}
//------------------
[ServiceFilter(typeof(CustomAuthorizeFilter))]
公共类AdminController:Controller
{
//在这里做点什么
}
它是否需要作为单例添加,或者可以使用临时服务添加。addtransient@Son_of_Sam:当然,它也可能是暂时的…这取决于您正在实施的场景。。。