Injecting a dependency into OWIN Middleware and pe

2019-07-17 09:02发布

问题:

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?

回答1:

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