title: How to create OWIN middleware per request
body: <p>I am implementing a custom owin middleware to add <code>CSP</code> header (content security policy) in response header. For <code>CSP</code> to work, the middleware needs to create a unique nonce value per request. So i have <code>NonceService</code> which creates nonce value. The custom OWIN middleware has dependency on NonceService.     </p>
  
  <p>However my problem is i'm not able to register custom middleware per request.  </p>
  
  <p>When i debug i noticed OWIN is <strong>NOT</strong> creating new instance of custom middleware per request and because of that same nonce value is being used for all the requests.  </p>
  
  <p>Below is my code</p>
  
  <p><strong>Nonce Service</strong></p>
  
  <pre><code>public interface INonceService
  {
      string GetNonce();
  }
  
  public class NonceService : INonceService
  {
       private static readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
      private readonly string _nonce;
  
      public NonceService(int nonceByteAmount = 32)
      {
          var nonceBytes = new byte[nonceByteAmount];
          _rng.GetBytes(nonceBytes);
          _nonce = Convert.ToBase64String(nonceBytes);
      }
  
      public string GetNonce()
      {
          return _nonce;
      }
  }
  </code></pre>
  
  <p><strong>OWIN Middleware &amp; Extension</strong></p>
  
  <pre><code>public class SecurityHeaderMiddleware : OwinMiddleware
  {
      private readonly INonceService _nonceService = null;
      public SecurityHeaderMiddleware(OwinMiddleware next, INonceService nonceService) : base(next)
      {
          _nonceService = nonceService;
      }
  
      public override async Task Invoke(IOwinContext context)
      {
          await Next.Invoke(context);
  
          var nonce = _nonceService.GetNonce();
          var csp = BuildCSPHeader(nonce);
          context.Response.Headers.Add(key, csp);
      }
  }
  
  public static class OwinExtensions
  {
      private const string SecurityHeaderRegistrationKey = "SecurityHeaders";
  
      public static IAppBuilder UseSecurityHeader(this IAppBuilder app, INonceService nonceService)
      {
          if (app == null)
              throw new ArgumentNullException("app");
  
          if (app.Properties.ContainsKey(SecurityHeaderRegistrationKey))
              return app;
  
          app.Use&lt;SecurityHeaderMiddleware&gt;(nonceService);
          app.Properties.Add(SecurityHeaderRegistrationKey, true);
          return app;
      }
  }
  </code></pre>
  
  <p>I am using Unity as conatiner, so i register INonceService using <code>PerRequestLifetimeManager</code></p>
  
  <pre><code>container.RegisterType&lt;INonceService, NonceService&gt;(new PerRequestLifetimeManager(), new InjectionConstructor(32));
  </code></pre>
  
  <p>and i register my custom middleware with OWIN in startup.cs</p>
  
  <pre><code>public partial class Startup
  {
      public void Configuration(IAppBuilder app)
      { 
          var nonceService = ServiceLocator.Current.GetInstance&lt;INonceService&gt;();
          app.UseSecurityHeader(nonceService);
      }
  }
  </code></pre>
  
  <p><strong>Note</strong>
  If creating per request OWIN middleware is not possible then at least how should i pass per request new instance of NonceService to middleware.</p>