Authorization Dependency Injection

I am creating an authorization rule / policy for my ASP.NET 5 MVC application. The creation was simple and fairly easy to use, and it works (with my basic tests). However, now I need my data context to be in this requirement.

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

I am registering IAuthorizationRequirement, as 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 is executed, MyContext does not know the connection strings that are used like this (further in Startup.cs ):

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

I use DI for these types differently (and it works).

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

I know what I'm doing wrong, but I don’t see how to do it right so that DI is involved in everything.

+7
c # dependency-injection asp.net-core entity-framework
source share
1 answer

How it always works. Submit a question and the answer comes shortly afterwards. Here, as for those who may run into my question.

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

All Articles