Neatest way to 'reset' all static variables in a .NET application

Horribleness aside, if I have a .NET webapp which has static variables scattered across multiple classes, what is neatest way to 'clear' them all back to null.

Off the top of my head, it would be to restart the application using

System.Web.HttpRuntime.UnloadAppDomain() 

Reasons behind the question - We are caching a few very large Dictionary collections which are expensive to create, and on the odd occasion need to be reset.

Answers


Unloading sounds the simplest way, but you wouldn't want to do that very frequently; frankly I would be very dubious of any routine requirement to do this.

If you wanted to do it without unloading, you'd have to look on a case-by-case basis to understand the implications. In particular, forcibly setting something to null that was set to a value by the static constructor / type initializer / static field initializer could thoroughly break your application.

Note that static variables are rarely suitable for web apps, except perhaps for caches (and then must be carefully managed).

If you genuinely do have data like this, rather than multiple static variables you might look at instance variables on a state class that is help as a pseudo-singleton - then you only have one reference to swap per cluster of data.

Something that might be worth considering is having an event somewhere that the static code can subscribe to once only when initializing themselves, then trigger the event when needed, i.e.

myStaticData = new SomeExpensiveThreadSafeCacheDictionary();
GlobalKillSwitch.ResetCache += delegate { myStaticData.Clear(); };

I use this

    public static void ResetAllStaticsVariables(Type type)
    {
        var fields = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Public);
        foreach (var fieldInfo in fields)
        {
            fieldInfo.SetValue(null, GetDefault(type));
        }
    }

    public static object GetDefault(Type type)
    {
        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }

        return null;
    }

Need Your Help

add variable in rewrite url

php

I got a rewritten url that looks like this:

Query or Expression for excluding certain values from DAL selection

google-app-engine data-access-layer web2py

I'm trying to exclude posts which have a tag named meta from my selection, by: