casbin-net / casbin-aspnetcore

Casbin.NET integration middleware and sample code for ASP.NET Core
https://github.com/casbin/Casbin.NET
Apache License 2.0
64 stars 20 forks source link

How to pass a custom EnforcerService or how to make dbcontext available to RequestTransformer #38

Closed slinders1985 closed 2 years ago

slinders1985 commented 2 years ago

I am trying to retrieve objects from our db, based on ids passed by the request, to the enforcer, so that these objects are passed to a custom function when evaluating a policy.

I have created a CustomRequestTransformer (base class BasicRequestTransformer). Two of the request values I retrieve within this transformer are the oid of the user and a reference id of a tenant. With these ids I want to be able to get the User and Customer object in our database. So that I can return these objects in the requestValues-object of TransfromAsync and so pass them on to the enforcer in DefaultEnforcerService (line 88).

Is there a way to pass the dbcontext with the CustomRequestTransformer through dependency injection when configuring the DefaultRequestTransformer in the services.AddCasbinAuthorization()? Or is there a way to pass a custom EnforcerService instead of the services.TryAddScoped<IEnforceService, DefaultEnforcerService>(); within AddCasbinAtuhorizationCore(). Or is there another way to enable this?

casbin-bot commented 2 years ago

@sagilio @xcaptain @huazhikui

hsluoyz commented 2 years ago

@sagilio

slinders1985 commented 2 years ago

At the moment I have found a - not so recommendable - solution, as the following warning is shown on the line var sp = services.BuildServiceProvider(); >> "ASP0000: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injection services as parameters to 'Configure'." In the DefaultEnforcerFactory we have the option of passing the IServiceProvider, but in DefaultRequestTransformer that option is not available.

image

Any suggestions?

sagilio commented 2 years ago
  1. You can get the DbContext from the HttpContext.RequestServices: image
  2. All services be added in the container by the TryAdd function, you can add your custom service before AddCasbinAtuhorizationCore(). Or replace it after AddCasbinAtuhorizationCore().
slinders1985 commented 2 years ago

@sagilio Thank you for this clarification! :pray: