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正在跨越一切利用。