0

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
    }
}
3
  • Can you post some example code? I don't understand your scenario. Commented Apr 12, 2012 at 11:00
  • Did you mean that the shared object should be created when a request begin and deleted when the request is processed ? Where does this object should be created ? Could you give a real example + code of your scenario plz ? Commented Apr 13, 2012 at 13:04
  • The shared object should can be lazy init. The shared object should be created when the object is accessed. Commented Apr 13, 2012 at 14:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i like the way you make this, very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.