title: OWIN Middleware and Dependency Injection Per Request with Unity in Asp.NET WebApi
body: <p>I'm trying to build some OWIN middleware that is resolved by Unity on a per request basis in Asp.NET WebApi. (Not DotNetCore!)</p>
  
  <p><strong>Problem #1:</strong>
  I can't figure out how to pass <code>next</code> to the constructor of the <code>OwinMiddleware</code> implementation. This code won't compile as <code>next</code> is <code>Func&lt;Task&gt;</code> and the constructor expects type <code>OwinMiddleware</code>.</p>
  
  <pre><code>public class CustomMiddleware : OwinMiddleware
  {
      public CustomMiddleware(OwinMiddleware next) : base(next)
      {
      }
  
      public override async Task Invoke(IOwinContext context)
      {
          await Next.Invoke(context);
      }
  }
  
  app.Use(async (context, next) =&gt;
  {
      var middleware = new CustomMiddleware(next);
      await middleware.Invoke(context);
  });
  </code></pre>
  
  <p>I've managed to get around this by not implementing <code>OwinMiddleware</code>, however this feels wrong. Surely there's a way to make this work correctly?</p>
  
  <p><strong>Problem #2:</strong>
  As mentioned before, I've sidestepped the <code>OwinMiddleware</code> implementation issue. Now I want to inject an object into <code>CustomMiddleware</code> and that <strong>same</strong> object scoped <strong>per request</strong> must be resolved by an <code>TestController</code> further down the request pipeline, however I'm seeing different instances of the object resolved in the  <code>CustomMiddleware</code> and <code>TestController</code> for the same request.</p>
  
  <pre><code>public class InjectedObject
  {
      public string Instance = Guid.NewGuid().ToString();
  }
  
  public class CustomMiddleware
  {
      private readonly InjectedObject _obj;
  
      public CustomMiddleware(InjectedObject obj)
      {
          _obj = obj;
      }
  
      public async Task Invoke(IOwinContext context, Func&lt;Task&gt; next)
      {
          //Do stuff with my object
          await next();
      }
  }
  </code></pre>
  
  <p>And within the app configuration method:</p>
  
  <pre><code>container.RegisterType&lt;CustomMiddleware&gt;(new HierarchicalLifetimeManager());
  container.RegisterType&lt;InjectedObject&gt;(new HierarchicalLifetimeManager());
  
  app.Use(async (context, next) =&gt;
  {
      var middleware = container.Resolve&lt;CustomMiddleware&gt;();
      await middleware.Invoke(context, next);
  });
  </code></pre>
  
  <p>And when the controller is called the InjectedObject is different to the one that was injected into CustomMiddleware.</p>
  
  <pre><code>public class TestController : ApiController
  {
      private readonly InjectedObject _obj;
  
      public TestController(InjectedObject obj)
      {
          _obj = obj;
      }
  }
  </code></pre>
  
  <p>Any ideas?</p>