使用Simple Injector将依赖项注入OWIN中间件并按Web请求 [英] Injecting a dependency into OWIN Middleware and per web-request with Simple Injector

查看:118
本文介绍了使用Simple Injector将依赖项注入OWIN中间件并按Web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何将所有依赖项最好地注入到我为Web API应用程序编写的自定义OWIN中间件中。一个简单的例子就是我正在使用的DbContext。我有一些可能需要根据请求进行查询的中间件。我遇到的问题是,我希望我的DbContext具有WebApiRequestLifestyle范围。我的DbContext是这样注册的:

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

显然,这不起作用:

container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

因为我在中间件中需要使用MobileDbContext,例如:

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?

推荐答案

文档显示了如何在范围内包装OWIN请求的示例:

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

这是在执行上下文范围内包装OWIN请求。现在您要做的就是将执行竞赛范围设置为默认范围内的生活方式,如下所示:

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

这篇关于使用Simple Injector将依赖项注入OWIN中间件并按Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆