Dependency Injection on AuthorizationOptions

时光总嘲笑我的痴心妄想 提交于 2019-12-21 09:24:24

问题


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>()));
    });


来源:https://stackoverflow.com/questions/32470047/dependency-injection-on-authorizationoptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!