是使用Singleton for Driver实例的好方法吗?

时间:2017-04-14 13:05:04

标签: c# selenium singleton

请考虑这种方法:

public class Driver
{
    public static IWebDriver Instance;
    public static IJavaScriptExecutor iJavaScriptExecutor;

    public static IWebDriver getInstance()
    {
        if (Instance == null)
        {
            Instance = new ChromeDriver(GetGoogleChromeDriverPath());
            iJavaScriptExecutor = Instance as IJavaScriptExecutor;
        }

        return Instance;
    }

    static string GetGoogleChromeDriverPath()
    {
        return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

使用Singleton for Driver实例是否很好?

编辑:

public sealed class Driver
{
    private Driver() { }

    public static IWebDriver Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() { }

        internal static readonly IWebDriver instance = new ChromeDriver(GetGoogleChromeDriverPath());
    }

    static string GetGoogleChromeDriverPath()
    {
        return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    }
}

因为Zohar Peled建议我将其更改为此版本。 如何将IJavaScriptExecutor实例添加到我的班级?

0 个答案:

没有答案