3

I am trying to work out how to best inject all of my dependencies into the custom OWIN Middleware I have written for a Web API Application. A simple example would be the DbContext I am using. I have some middleware that needs to potentially query based on the request. The issue I have is that I want my DbContext to otherwise have a WebApiRequestLifestyle scope. My DbContext is registered as such:

container.Register<MobileDbContext>(Lifestyle.Scoped);

Obviously, this does not work:

container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

Because I need the MobileDbContext in my Middleware using something like:

app.CreatePerOwinContext(() =>
{
    return container.GetInstance<MobileDbContext>();
};

I tried a hybrid lifestyle, but that also didn't work because I don't think the Middleware is technically something that can fall under a "scoped" lifestyle. It is probably closer to a singleton, I would think.

Is there a better way to design my app to avoid this problem or address it with some sort of custom scoped lifestyle?

Carson
  • 1,169
  • 13
  • 36

1 Answers1

3

The documentation shows an example of how to wrap an OWIN request in a scope:

public void Configuration(IAppBuilder app) {
    app.Use(async (context, next) => {
        using (AsyncScopedLifedtyle.BeginScope (container)) {
            await next();
        }
    });
}

What this does is wrapping an OWIN request in an execution context scope. All you have to do now is make the execution contest scope the default scoped lifestyle as follows:

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
Steven
  • 166,672
  • 24
  • 332
  • 435
  • 1
    Wow, easy. I didn't read the docs well enough. Thanks a bunch! – Carson May 16 '16 at 15:34
  • What if I want to get the same instance to be used in both the middleware and in any of the API controllers? The problem with this approach is - it injects a singleton instance in the middleware, and webapi scoped instance in the API controllers – Gokulnath Sep 09 '16 at 15:54