Storing context object in Request object, is it di

2019-07-27 10:51发布

问题:

I am writing a MVC3 application, using NInject DI and repository pattern. Ninject is set up so that the repositories have a per-request lifetime.

I am putting the context object into the Http Request object, using the following code:

    public static MessengerEntities GetContext()
    {
        if (!HttpContext.Current.Items.Contains("_db_context"))
        {
            HttpContext.Current.Items.Add("_db_context", new MessengerEntities());
        }
        return (MessengerEntities)HttpContext.Current.Items["_db_context"];
    }

Then each repository calls this procedure to get either an existing or a new context object, e.g.:

public class TestRepository : ITestRepository
{
    private MessengerEntities context = ContextHelper.GetContext();

    #region ITestRepository Members
    private string _testProperty = "blah";
    public string testProperty
    {
        get
        {
            _testProperty = context.UserLogins.Where(n => n.inactive == null || !n.inactive.Value).ToList().Count.ToString();
            return _testProperty;
        }
        set
        {
            _testProperty = value;
        }
    }

    #endregion
}

(Later on, I plan to use a generic IRepository pattern, but for now I am just using this test repository.)

My question is: when the Request object is disposed of, will it also dispose of the context object in the Items collection? In other words, will it call Dispose on each object that may be stored in that collection?

I know there are a lot of discussions about this issue here, but they all seem to involve scenarios that are not quite the same as mine, so it's kind of hard to divine the answer.