【问题标题】:Dependency Injection on AuthorizationOptionsAuthorizationOptions 上的依赖注入
【发布时间】:2015-12-04 20:40:48
【问题描述】:

我正在为我的 ASP.NET 5 MVC 应用程序创建授权规则/策略。创建它很简单,很容易做到,而且它正在工作(通过我的基本测试)。但是,我现在需要将我的数据上下文纳入需求中。

我在我的 IAuthorizationRequirement 实现中创建了一个构造函数,它接受一个实现 DbContextMyContext 对象。

我正在我的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


    【解决方案1】:

    它总是这样工作的。发布问题,答案很快就会出现。以下是可能遇到我问题的人的方法。

    services.Configure<AuthorizationOptions>(options => 
        {
            options.AddPolicy("AllowProfileManagement", policy => policy.Requirements.Add(
                services.BuildServiceProvider().GetRequiredService< AllowProfileManagementRequirement>()));
        });
    

    【讨论】:

    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2014-06-12
    相关资源
    最近更新 更多