7
我正在为我的ASP.NET 5 MVC应用程序创建授权规则/策略。创建它很简单,很容易做到,它正在工作(用我的基本测试)。但是,我现在需要将我的数据上下文放入需求中。AuthorizationOptions上的依赖注入
我在我的IAuthorizationRequirement实现中创建了一个构造函数,该实现需要一个MyContext
对象,它实现了DbContext
。
我正在注册我的Startup.cs
文件中的IAuthorizationRequirement。
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正在跨越一切利用。