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.
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>()));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With