Data caching per request in Owin application
解答1
Finally I found OwinRequestScopeContext. Very simple to use.
In the Startup class:
app.UseRequestScopeContext(); //依赖于NuGet上的这个package https://www.nuget.org/packages/OwinRequestScopeContext/
Then I can add per request cache like this:
OwinRequestScopeContext.Current.Items["myclient"] = new Client();
Then anywhere in my code I can do (just like HttpContext.Current):
var currentClient = OwinRequestScopeContext.Current.Items["myclient"] as Client;
Here is the source code if you're curious. It uses CallContext.LogicalGetData and LogicalSetData. Does any one see any problem with this approach of caching request data?
源码https://github.com/neuecc/OwinRequestScopeContext/
需要注意app.Use的时机,需要放在webapi之前,否则current会是空
app.UseAutofacMiddleware(container);
app.UseRequestScopeContext();
app.UseAutofacWebApi(config);
app.UseWebApi(config);
关于原理部分另外一个https://github.com/DavidLievrouw/OwinRequestScopeContext 中提到 http://odetocode.com/Articles/112.aspx
解答2
ou just need to use OwinContext for this:
From your middleware:
public class HelloWorldMiddleware : OwinMiddleware
{
public HelloWorldMiddleware (OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
context.Set("Hello", "World");
await Next.Invoke(context);
}
}
From MVC or WebApi:
Request.GetOwinContext().Get<string>("Hello");
Should I use OwinContext's Environment to hold application specific data per request
OWIN environment dictionary can be used to store per-request data. Properties collection of the request object can be used to do the same.
The main difference is OWIN environment dictionary is an OWIN concept and is applicable to any middleware running in a OWIN host. Properties collection of the request object is an ASP.NET Web API concept and is applicable only to that specific framework.
BTW, ASP.NET Web API itself runs as a middleware in OWIN pipeline. So, to answer your question, you cannot access the request properties collection of Web API from your middleware because it is applicable only to Web API middleware (or that specific framework).
If you want to write your cross-cutting concern stuff as OWIN middleware you have to use OWIN environment dictionary. If Web API extension points like a filter or a message handler is okay, then you can use the properties collection.
Obviously, anything you write leveraging Web API extension points is applicable only to Web API whereas OWIN middleware is applicable to any kind of app running in OWIN pipeline and that includes Web API.
这个回答下,有人提到了上一个链接中的解答1