Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection on AuthorizationOptions

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.

like image 746
JasCav Avatar asked Sep 09 '15 02:09

JasCav


1 Answers

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>()));
    });
like image 160
JasCav Avatar answered Oct 10 '22 05:10

JasCav