Pregunta

I have the following code to ensure only a single instance of a browser for Watin.

public sealed class BrowserIE
{

    static readonly IE _Instance = new IE();

    static BrowserIE()
    {
    }

    BrowserIE()
    {
    }

    public static IE Instance
    {
        get { return _Instance; }
    }
}

but I can't figure out where to apply the settings inside this class. How/where can I apply the following setting to the code above so they take affect before

Settings.Instance.MakeNewIeInstanceVisible = false;

I know I can use the following inside a method which works but I can't get the syntax right in my example above where _Instance is static readonly.

Settings.Instance.MakeNewIeInstanceVisible = false;
_Instance = new IE();
¿Fue útil?

Solución

Why don't you make use of the static constructor?

public sealed class BrowserIE
{
    static readonly IE _Instance;

    static BrowserIE()
    {
        Settings.Instance.MakeNewIeInstanceVisible = false;
        _Instance = new IE();
    }

    BrowserIE()
    {
    }

    public static IE Instance
    {
        get { return _Instance; }
    }
}

Otros consejos

If you want to implement a thread save singleton and you use .NET 4.0 you could use the System.Lazy<T> class

public sealed class BrowserIE
{
    private static readonly Lazy<BrowserIE> _singleInstance = new Lazy<BrowserIE>(() => new BrowserIE());

    private BrowserIE() { }

    public static BrowserIEInstance
    {
        get { return _singleInstance.Value; }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top