Dependency Injection on AuthorizationOptions

2020-07-06 08:35发布

问题:

I am creating an authorization rule/policy for my ASP.NET 5 MVC application. Creating it was straightforward and pretty easy to do, and it is working (with my basic tests). However, I now need to get my data context into the requirement.

I created a constructor in my IAuthorizationRequirement implementation which takes a MyContext object which implements DbContext.

I am registering the IAuthorizationRequirement like so in my Startup.cs file.

services.Configure<AuthorizationOptions>(options => 
    {
        options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add(
            new AllowProfileManagementRequirement(new MyRepository(new MyContext()))));
    });

Unfortunately, when my rule runs, MyContext is unaware of the connection strings which are used like so (farther up in Startup.cs):

services.AddEntityFramework()
    .AddSqlServer()
    .AddDbContext<MemorialContext>(options =>
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

I am using DI for these types otherwise (and it is working).

services.AddTransient<MyRepository>(
        provider => new MyRepository(provider.GetRequiredService<MyContext>()));

I know what I am doing is not right, but I don't see how to make this right so that DI is being leveraged across everything.

回答1:

It's how it always works. Post the question, and the answer comes shortly after. Here's how for those who may come across my question.

services.Configure<AuthorizationOptions>(options => 
    {
        options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add(
            services.BuildServiceProvider().GetRequiredService< AllowProfileManagementRequirement>()));
    });