AuthorizationOptions上的dependency injection
我正在为我的ASP.NET 5 MVC应用程序创建授权规则/策略。 创建它很简单,很容易做到,它正在工作(我的基本测试)。 但是,我现在需要将我的数据上下文纳入需求。
我在IAuthorizationRequirement实现中创建了一个构造函数,它接受一个实现DbContext
的MyContext
对象。
我正在我的Startup.cs
文件中注册IAuthorizationRequirement。
services.Configure(options => { options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add( new AllowProfileManagementRequirement(new MyRepository(new MyContext())))); });
不幸的是,当我的规则运行时, MyContext
不知道所使用的连接字符串(在Startup.cs
更远):
services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
我正在使用DI这些类型(并且它正在工作)。
services.AddTransient( provider => new MyRepository(provider.GetRequiredService()));
我知道我在做什么是不对的,但我不知道如何做到这一点,以便DI被用于所有事情。
这是它总是有效的方式。 发布问题,答案很快就会出现。 以下是那些可能遇到我问题的人的方式。
services.Configure(options => { options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add( services.BuildServiceProvider().GetRequiredService< AllowProfileManagementRequirement>())); });