0

私は C# MVC3 サイトを持っています。ただし、同じリクエストで複数のクラスにオブジェクトを共有する必要がありました。
他のリクエストは共有オブジェクトにアクセスできません/存在することを知りません。
リクエストが終了したら、共有オブジェクトを削除する必要があります。

このコード例では、1 つのリクエストのみでオブジェクトを共有するのではなく、各リクエストにオブジェクトを渡すことができます。

Class ShareObjects
{
    private static SomeThing _Data = null;
    public static SomeThing Data
    {
        get
        {
            if (_Data == null)
            {
                _Data = new SomeThing();
            }

            return _Data;
        }
    }
}

Class ObjectA
{
    public ObjectA()
    {
        var data = ShareObjects.Data;
        //Do stuff
    }
}

Class ObjectB
{
    public ObjectB()
    {
        var data = ShareObjects.Data;
        //Do stuff
    }
}
4

1 に答える 1

2

コードを global.asax.cs に追加できます。

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var customContext = CustomHttpContext.Initialize(new HttpContextWrapper( Context) );
}

上記のコードでわかるように、これを HttpContext にフックしました。CustomHttpContext Initialize ルーチンは次のようになります。

public static CustomHttpContext Initialize(HttpContextBase httpContextBase)
{
    Guard.IsNotNull(httpContextBase, "httpContext");

    // initialize only once
    if (! httpContextBase.Items.Contains(key))
    {
        CustomHttpContext newCustomHttpContext = new CustomHttpContext();
        httpContextBase.Items[key] = newCustomHttpContext;
        return newCustomHttpContext;
    }
    return Get(httpContextBase);
}

これが完了すると。コンテキストを提供することで、CustomHttpContext を呼び出すことができます。

CustomHttpContext.Get(HttpContext).PropA;

お役に立てれば。

于 2012-04-19T08:14:14.117 に答える