Is this one of them circular links?

I want to add an easily accessible helper class to my asp mvc page. I created a class called "Repositories". It has a static "Current" property that does the following:

public static readonly Repositories Current
        if(HttpContext.Current.Items["Repositories"] == null)
            HttpContext.Current.Items["Repositories"] = new Repositories(HttpContext.Current);
        return (Repositories)HttpContext.Current.Items["Repositories"];


The point is that the class has static helper functions that use the current instance of the class (bound to the current httpcontext). The helper functions do all sorts of things, so I wanted to organize them this way because it provides prettier code in controllers and I have potential access to all database stores (actual descriptor objects are only created when this context is accessed, though).

Anyway, as you can see, the constructor takes an HttpContext as an argument, which is then stored in a private class field, so I have less typing. This means that an instance of the Repositories class refers to an instance of the HttpContext class and vice versa. When the HttpContext is discarded, does that mean it is still in memory, being kept circularly referenced by the repository instance?


source to share

1 answer

An orphaned circular reference does not force objects to remain in memory.

If you do this:

class A
    public B b;

        Console.WriteLine("COLLECTED A!");

class B
    public A a;

        Console.WriteLine("COLLECTED B!");


and run this code:

var a = new A();
var b = new B();

a.b = b;
b.a = a;

a = null;
b = null;



Both instances can (and will) be garbage collected. You will get something similar to the following output:





All Articles