【发布时间】:2015-12-04 20:40:48
【问题描述】:
我正在为我的 ASP.NET 5 MVC 应用程序创建授权规则/策略。创建它很简单,很容易做到,而且它正在工作(通过我的基本测试)。但是,我现在需要将我的数据上下文纳入需求中。
我在我的 IAuthorizationRequirement 实现中创建了一个构造函数,它接受一个实现 DbContext 的 MyContext 对象。
我正在我的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 在所有方面都得到利用。
【问题讨论】:
标签: c# asp.net entity-framework dependency-injection asp.net-core