依赖注入授权选项 [英] Dependency Injection on AuthorizationOptions
问题描述
我在我的IAuthorizationRequirement实现中创建了一个构造函数,它实现了一个 MyContext
对象实现 DbContext
。
我在我的<$ c $中注册了IAuthorizationRequirement c> Startup.cs 文件。
services.Configure< AuthorizationOptions>(options =>
{
options.AddPolicy(AllowProfileManagement,policy => policy.Requirements.Add(
new AllowProfileManagementRequirement(new MyRepository(new MyContext())));
} );
不幸的是,当我的规则运行时, MyContext
不知道使用的连接字符串(在 Startup.cs
中更远):
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext< MemorialContext>(options =>
options.UseSqlServer(Configuration [Data:DefaultConnection:ConnectionString ]));
我正在使用DI这些类型,否则(它正在工作)。
services.AddTransient< MyRepository>(
provider => new MyRepository(provider.GetRequiredService< MyContext>()));
我知道我在做什么是不对的,但我看不到如何使这个权利所以DI正在跨越一切。
这是它的工作原理。发布问题,答复不久之后。以下是可能遇到我问题的人的方法。
services.Configure< AuthorizationOptions>(options =>
{
options.AddPolicy(AllowProfileManagement,policy => policy.Requirements.Add(
services.BuildServiceProvider()。GetRequiredService& AllowProfileManagementRequirement>()));
});
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>()));
});
这篇关于依赖注入授权选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!