Skip to content

Having lots of issues with DI #80

@VictorioBerra

Description

@VictorioBerra

Hello, I am trying to DI the enforcer and do things like Load/Add/Remove Policys.

    public class CasbinDbContext(DbContextOptions<CasbinDbContext> options)
        : CasbinDbContext<int>(options)
    {
    }

    builder.Services.AddDbContext<CasbinDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

    // https://github.com/casbin-net/casbin-aspnetcore/blob/master/samples/WebApplicationWithEfcoreSample/Startup.cs
    builder.Services.AddCasbinAuthorization(options =>
    {
        options.DefaultModelPath = "model.conf";

        options.DefaultEnforcerFactory = (p, m) =>
            new Enforcer(m, new EFCoreAdapter<int>(p.GetRequiredService<CasbinDbContext>()));
        options.DefaultRequestTransformerType = typeof(BasicRequestTransformer);
    });

    // ...

    public class IndexModel(IEnforcerProvider enforcerProvider) : PageModel
    {
        private readonly IEnforcer enforcer = enforcerProvider.GetEnforcer()!;
        public void OnGet()
        {
            this.enforcer.LoadPolicy();
        }
    }

Error:

ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'CasbinDbContext'.

Metadata

Metadata

Assignees

Labels

questionFurther information is requestedreleased

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions