title: Injecting a value from MVC controllers
body: <p>Our repositories and services are currently being injected into our controllers via a Unity container (using the Web API MVC bootstrapper).</p>
  
  <pre><code>public class AnnouncementsController : BaseApiController
  {
      protected IAnnouncementRepository AnnouncementRepository{ get; set; }
  
      public AnnouncementsController (IAnnouncementRepository announcementRepository)
          : base()
      {
          this.AnnouncementRepository = announcementRepository;
      }
  
      public HttpResponseMessage Post([FromBody]GetAnnouncementsModel model)
      {
          var announcements = AnnouncementRepository.GetByType(model.AnnouncementType);
          // ... 
      }
  }
  </code></pre>
  
  <p><strong>A new requirement has arisen:</strong>  All input models (e.g. <code>GetAnnouncementsModel</code>) now need to have an <code>AccessToken</code>.</p>
  
  <p>Why? So that results from repositories are filtered according to data rights.  Clients are restriction on what data they can consume.</p>
  
  <h2>Bad Solution - Pass in token as a method parameter</h2>
  
  <p>One solution is to include an <code>AccessToken</code> parameter to every repository or service call.  This is not a good solution.  We have to implement this in hundreds of methods.  An example of this parameter:</p>
  
  <pre><code>public HttpResponseMessage Post([FromBody]GetAnnouncementsModel model)
  {
      var announcements = AnnouncementRepository.GetByType(model.AccessToken, model.AnnouncementType);
      // ... 
  }
  </code></pre>
  
  <h2>Better Solution - Inject token during resolution</h2>
  
  <p>A better solution would be to provide the <code>AccessToken</code> in the repository constructors and have some base implementation that does the filtering logic implicitly.  </p>
  
  <p>But how could I do this with dependency injection?  The constructor is resolved and called by the Unity container.  How could I inject the property value of an input model into this process?</p>
  
  <pre><code>container.RegisterType&lt;IAnnouncementRepository, AnnouncementRepository&gt;(
      new InjectionConstructor(
          new InjectionParameter&lt;Guid&gt;(AccessToken)
      )
  );
  </code></pre>