简体   繁体   English

将依赖项注入到OWIN中间件中,并使用Simple Injector根据每个Web请求

[英]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. 我正在尝试找出如何最好地将我的所有依赖项注入到我为Web API应用程序编写的自定义OWIN中间件中。 A simple example would be the DbContext I am using. 一个简单的例子就是我正在使用的DbContext。 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. 我遇到的问题是,我希望我的DbContext具有WebApiRequestLifestyle范围。 My DbContext is registered as such: 我的DbContext注册如下:

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: 因为我需要使用类似以下内容的中间件中的MobileDbContext:

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: 文档显示了如何在范围内包装OWIN请求的示例:

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. 这样做是将OWIN请求包装在执行上下文范围内。 All you have to do now is make the execution contest scope the default scoped lifestyle as follows: 您现在要做的就是将执行竞赛范围设置为默认范围内的生活方式,如下所示:

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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