title: Injecting ModelState into Service
body: <p>I am trying to inject the ModelState of the controller into my Service layer to add business logic related validation errors (e.g. entry already exists).</p>
  
  <p>For this I created a new IValidationDictionary that gets injected into my service through an Initialize() function. Nothing new at all and judging by my google searches something quite some people do in MVC.</p>
  
  <p>The Controller constructor looks like this:</p>
  
  <pre><code>public AccountController(IAccountService accountService)
  {
     _accountService = accountService;
     _accountService.Initialize(new ValidationDictionary(ModelState));
  }
  </code></pre>
  
  <p>This all works fine and I can add errors in my service. The issue comes when leaving the service again. At that point none of my errors are present in the controller ModelState. After some debugging I found out that the ModelState in the constructor of the controller is not the same as in the Action. At some point it seems to create a new ModelState.</p>
  
  <p>One alternative seems to be to call the Initialize() to inject the ModelState at start of every Action. Before I do that, I wanted to ask if anyone has a more elegant way (as in less to type) of solving this.</p>
  
  <p>Edit:
  The IValidationDictionary:
  On buisness layer:</p>
  
  <pre><code>public interface IValidationDictionary
      {
          void AddError(string key, string message);
          bool IsValid { get; }
      }
  </code></pre>
  
  <p>In controller:</p>
  
  <pre><code>public class ValidationDictionary : IValidationDictionary
      {
          private ModelStateDictionary _modelState;
  
          public ValidationDictionary(ModelStateDictionary modelState)
          {
              _modelState = modelState;
          }
  
          public bool IsValid
          {
              get
              {
                  return _modelState.IsValid;
              }
          }
  
          public void AddError(string key, string message)
          {
              _modelState.AddModelError(key, message);
          }
      }
  </code></pre>