c# - 领域驱动设计 : access a configured value from an Entity without using a Service Locator

标签 c# dependency-injection domain-driven-design service-locator

我有一个 User 实体,它有一个 HasCompletedSecurity 属性,它指示特定的 User 是否已经回答了系统。系统要求的安全问题数量是可配置的,并可从配置文件中检索。 User类应该如何访问配置的信息?

我目前有一个 IConfigurationService 接口(interface),在该接口(interface)后面我有使用 ConfigurationManager 或 Azure 等效项(如果可用)的实现。我已经通过静态 InjectionService 类封装了对我的 DI 容器的访问,目前正在解析配置值,如下所示:

public class User
{
    private static readonly IConfigurationService _configurationService = 
        InjectionService.Resolve<IConfigurationService>();

    public bool HasCompletedSecurity
    {
        get
        {
            // Uses the static _configurationService to get the 
            // configured value:
            int numberOfRequiredResponses = 
                GetConfiguredNumberOfRequiredResponses();

            return this.SecurityQuestionResponses.Count()
                >=
                GetConfiguredNumberOfRequiredResponses();
        }
    }
}

这当然是 ServiceLocator anti-pattern 的一个例子,我有点不喜欢它。静态依赖使得单元测试任何使用此类的东西都很尴尬。

我正在使用 Entity Framework 并从 here 中得到启发我不想通过 DI 容器传递我的实体来为它们提供依赖项,所以...我应该如何访问配置的值?

编辑:一方面是这个确切的例子(我非常感谢关于它的正确架构的建议),我感兴趣的更大的问题是你如何管理非实体对服务的静态引用?只是以一种您永远不需要的方式来构建实体的答案是什么?

最佳答案

下面是我将如何定义用户类:

public class User
{
    public bool HasCompletedSecurity { get; set; }

    // other members...
}

说真的,这是一个更好的解决方案,因为它在时间维度 上解耦了值。考虑一下:如果用户在 2010 年完成了所有安全问题,而您后来更改了业务规则,那么您是否要使现有用户无效?

在大多数情况下,记录并坚持用户在过去某个时间完成了当时有效的安全程序可能更为合理。这样,您就不会打扰现有用户。

关于c# - 领域驱动设计 : access a configured value from an Entity without using a Service Locator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080336/

相关文章:

c# - Autofac:IEnumerable<IInterface> 将始终返回从 IInterface 派生的对象列表?

c# - 统一配置约定

domain-driven-design - 将引用的聚合根转换为另一个聚合根

c# - 使用 Entity Framework Core 数据库优先方法,如何将实体与基础设施层分离?

symfony - 创建一个实现 ContainerAwareInterface 的基础 Controller 类

c# - 什么是 GC 漏洞?

node.js - Node.JS服务层设计

c# - 聚合根和聚合的代码示例

c# - 如何为 ListviewSubItem 设置工具提示

c# - 动态加载到另一个页面时无法调用用户控件按钮单击事件