MingHong Zheng
MingHong Zheng

Reputation: 185

.NET Core how to DI DbContext to AuthrozationFilter

like as title

I setting db context on Startup.cs

services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionStr));

and I want using it on AuthrozationFilter constructor like this

    public class AuthrozationFilter : Attribute, IAuthorizationFilter
    {
      private readonly MyContext _db;

      public AuthrozationFilter(MyContext db)
      {
        this._db = db;
      }
    }

but it doesn't work, how to do that ?

Upvotes: 3

Views: 1169

Answers (2)

KyleUp
KyleUp

Reputation: 1703

Found another way to do it. Under the covers this is wrapping ServiceFilter

Use the AddService api on Action<MvcOptions>

serviceCollection.AddControllers(c => c.Filters.AddService<AuthrozationFilter>())

Need to register your service with dependency injection

serviceCollection.AddScoped<AuthrozationFilter>();

Then inject via the constructor

public class AuthrozationFilter :  IAuthorizationFilter
{
    private readonly MyContext _db;

    public AuthrozationFilter(MyContext db)
    {
        this._db = db;
    }
}

Adds the filter to all controllers. If you need more targeted, probably use ServiceFilterAttribute directly.

Upvotes: 0

Nan Yu
Nan Yu

Reputation: 27538

You can use service location to resolve components from the built-in IoC container by using RequestServices.GetService:

public class AuthrozationFilter : Attribute, IAuthorizationFilter
{

    public void OnAuthorization(AuthorizationFilterContext context)
    {
       var dbcontext=  context.HttpContext.RequestServices.GetRequiredService<MyContext>();

    }
}

Or you can use ServiceFilter/TypeFilter :

public class AuthrozationFilter :  IAuthorizationFilter
{
    private readonly MyContext _db;

    public AuthrozationFilter(MyContext db)
    {
        this._db = db;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {

    }
}

And add [TypeFilter(typeof(AuthrozationFilter))] on controllers/actions . Please refer to below documents for filters in asp.net core :

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1 https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core

Upvotes: 5

Related Questions