Using a Singleton Pattern with Eclipse Scripting API

When writing an app with a UI component, you can be switching through windows or form controls and each of those might need access to the application context (where all the data is located). How do you accomplish this?

One way is to set up some kind of routing system where one window passes the context to the next and so on. This gets tedious and is difficult with larger apps. I have found that it is often helpful to have a separate class that controls access to the application context.

A Simple Singleton Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VMS.TPS.Common.Model.API;
 
namespace Cardan.ESAPI
{
    public class ESAPIApplication
    {
        private static readonly Lazy<ESAPIApplication> _instance = new Lazy<ESAPIApplication>(() => new ESAPIApplication());
 
        // private to prevent direct instantiation.
        private ESAPIApplication()
        {
            Context = Application.CreateApplication(null, null);
        }
 
        public Application Context { get; private set; }
        public static bool IsLoaded { get; set; }
 
        // accessor for instance
        public static ESAPIApplication Instance
        {
            get
            {
IsLoaded = true;
                return _instance.Value;
            }
        }
 
        public static void Dispose()
        {
            if (IsLoaded) { Instance.Context.Dispose(); }
        }
    }
}

Then when when you need the context, you just call:

    public partial class Form1 : Form
    {
        VMS.TPS.Common.Model.API.Application app;
        public Form1()
        {
            InitializeComponent();
            app = ESAPIApplication.Instance.Context;
        }
    }

Some Notes On Use

It is lazily loaded, so it will not get called until you need it. Also, the first time will require authentication, unless you have input username and password on the Application.CreateApplication method. After that. it stays loaded and is always ready to go. Lastly, be sure to use the Dispose method when you are through (when your app closes). Otherwise it will crash.

Last edited Jul 1, 2014 at 2:17 AM by rexcardan, version 2