简体   繁体   中英

Injecting a dependency into OWIN Middleware and per web-request with Simple Injector

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM