Search code examples
c#dependency-injectiondomain-driven-designservice-locator

Domain Driven Design: access a configured value from an Entity without using a Service Locator


I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system. The number of security questions the system requires is configurable and retrieved from a config file. How should the User class access the configured information?

I currently have an IConfigurationService interface behind which I have implementations which use the ConfigurationManager or the Azure equivalent if it is available. I've encapsulated access to my DI container through a static InjectionService class, and am currently resolving the configured value like so:

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();
        }
    }
}

This is of course an example of the ServiceLocator anti-pattern, and I don't like it one bit. The static dependency makes unit testing anything which uses this class awkward.

I'm using the Entity Framework and taking a cue from here I don't want to pass my entities through a DI container to give them their dependencies, so... how should I be accessing the configured value instead?

Edit: With this exact example to one side (and I do appreciate the suggestions as to the correct architecture for it), the larger question I'm interested in is how do you manage non-static references to services from entities? Is the answer to just architect the entities in such a way that you never need to?


Solution

  • Here's how I would define the User class:

    public class User
    {
        public bool HasCompletedSecurity { get; set; }
    
        // other members...
    }
    

    Seriously, this is a better solution because it decouples the value along the temporal dimension. Consider this: if a user completed all security questions in 2010 and you later on change the business rule, are you then going to invalidate the existing user?

    In most cases it would probably be more reasonable to record and persist that sometime in the past, the user completed the security procedure that was in effect at that time. In that way, you don't bother existing users.