0

Please consider this approach:

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);

Is it good approach to use Singleton for Driver instance ?

Edit:

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);
    }
}

So as Zohar Peled suggested i change it to this version. How can i add IJavaScriptExecutor instance to my class ?

user979033
  • 5,430
  • 7
  • 32
  • 50
  • Almost *never* it is a good idea to use a *Singleton*. That is why some consider it an [anti-pattern](http://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern). – Willem Van Onsem Apr 14 '17 at 13:06
  • Any other options ? – user979033 Apr 14 '17 at 13:08
  • This is a poor implementation of the singelton design pattern. [Read this article](http://csharpindepth.com/Articles/General/Singleton.aspx) by Jon Skeet and adopt a better one. – Zohar Peled Apr 14 '17 at 13:08
  • Any recommended version ? – user979033 Apr 14 '17 at 13:15
  • Yes. The version where you read the article and make up your own opinion, or just do what Jon said. – Zohar Peled Apr 14 '17 at 13:20
  • Please see my update – user979033 Apr 14 '17 at 13:24
  • You can cast IWebdriver to IJavaScriptExecutor safely. (IJavaScriptExecutor)Instance.ExecuteScript(ScriptGoesHere); – Michiel Bugher May 10 '17 at 21:47
  • As for your initial question about a singleton being a good idea, personally, I perter to use dependency injection. You would register an instance of the driver (So, still technically a singleton) that is injected into the constructor of any other class that requires it. Here's an example that could get you started: https://softwareengineering.stackexchange.com/questions/177649/what-is-constructor-injection – Michiel Bugher May 10 '17 at 21:50

0 Answers0