I have an IFoo
instance which I need to use as per request instance. Here is how my startup class look like:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");
app.Use<RandomTextMiddleware>()
.UseWebApi(config);
}
RandomTextMiddleware
is a pass-through middleware and I need an instance of IFoo
implementation there. I also need an instance of IFoo
implementation inside my Web API pipeline.
How would you solve this problem so that I have the same instance of IFoo
implementation inside the RandomTextMiddleware
and the Web API pipeline per HTTP request?
The HTTP request has a much longer lifetime than the time it spends in your Owin pipeline. The HTTP Request is created by the client, it passes through the local client proxy cache, it goes through corporate proxies, through your ISPs public caching infrastructure, through your reverse proxy. Owin middleware is just another intermediary in that huge pipeline that extends from client to origin server. It just happens to run in the same process as your application. The fact that you can share state between owin middleware doesn't mean you should.
Maybe tomorrow, you will need to load balance your application servers and it makes more sense to run that piece of middleware on the reverse proxy rather than running an instance on each app server. If you have coupling between your middleware, that is going to make it harder to move.