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?
Just for the record, IMO (which is likely not that of many others) I don't think you should do this. Sharing state that is not part of the HTTP request/response message between middleware is a violation of the self-descriptive constraint and the layering constraint.
Consider for a moment that you want to add a piece of caching middleware. If your request/response pipeline is using state that is not part of the HTTP message then chances are the caching middleware is not going to cache that additional state. When a request comes in and gets a cache hit, the response will be missing the additional state.
Keeping Owin middleware as "pure" HTTP middleware will maximize the reusability of the middleware. It also provides a useful distinction between Owin middleware and application level middleware like HttpMessageHandlers and FUBU behaviours. In those application level pieces of middleware you are free to share state as there is an expectation that you are living within an application that has a shared set of dependencies.