リクエストごとにログ オブジェクトを保存する方法が必要です。HttpContext を使用して、これをアイテム ディクショナリに追加します。できるなら、これに HttpContext を持ち込みたくありません。以下のコードは、オブジェクトを OwinContext の Environment プロパティに格納する Unity LifeTimeManager に提案するもので、Owin ミドルウェアでアクセスできます。
public class OwinContextLifetimeManager : LifetimeManager
{
private string key = (new Guid()).ToString();
private IDictionary<string, object> environment;
public OwinContextLifetimeManager(IDictionary<string, object> environment)
{
this.environment = environment;
}
public override object GetValue()
{
if (environment != null && environment.ContainsKey(key))
return environment[key];
else
return null;
}
public override void RemoveValue()
{
if (environment != null)
environment.Remove(key);
}
public override void SetValue(object newValue)
{
if (environment != null)
environment[key] = newValue;
}
}
次に、ミドルウェアから次のように使用できます。
container.RegisterType<IRequestLog, RequestLog>(new OwinContextLifetimeManager(environment));
Owin によって既に予約されているものを除いて、任意のキーを選択できることに気づきました。この目的で OwinContext.Environment を使用してはいけない理由はありますか? MSDN のドキュメントは、このベスト プラクティスについて曖昧です。
ここでの Darrel Miller の回答: How should I store per request data when using OWIN to Self-Host ASP.NET Web API を使用すると、要求オブジェクトのプロパティ コレクションが最適であると思います。ミドルウェアからこのオブジェクトにアクセスするにはどうすればよいですか?