user554712
user554712

Reputation: 211

How to share objects to classes in same request with C# MVC3

I have a C# MVC3 site. However, I needed to share objects to multiple classes in same request.
The other requests cannot access / do not know the shared objects exist.
After the request end, the shared objects should be deleted.

This example code can the object to each request instead of sharing object in one request only.

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
    }
}

Upvotes: 0

Views: 619

Answers (1)

amaters
amaters

Reputation: 2316

you can add your code to the global.asax.cs:

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

What we did was hook it on the HttpContext as you can see in the code above. The CustomHttpContext Initialize routine looks like this:

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

When this is done. You are able to call CustomHttpContext by providing a context:

CustomHttpContext.Get(HttpContext).PropA;

Hope this helps.

Upvotes: 2

Related Questions