Context and System.IDisposable

Can be used to deliver context parameters if it is not possible to do it via usual method parameters.
Runnable job, which defines context:
final class VKTest
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        info('Start using');
        using(VKTestContext context = new VKTestContext())
        {
            context.boolProperty = true;
            
            VKTestExecutable exec = new VKTestExecutable();
            exec.performAction();
        }

        VKTestExecutable exec = new VKTestExecutable();
        exec.performAction();
        info('End using');

        // try-finally alternative 
        info('Start try');
        VKTestContext context = new VKTestContext();
        try
        {
            context.boolProperty = true;
            exec = new VKTestExecutable();
            exec.performAction();
        }
        finally
        {
            context.dispose();
            context = null;
        }
        exec = new VKTestExecutable();
        exec.performAction();
        info('End try');
    }

}
Execution infolog:
Start using
True
False
End using
Start try
True
False
End try

Context class with required parameters/logic
class VKTestContext implements System.IDisposable
{
    static VKTestContext instance;
    public boolean boolProperty;

    public void new()
    {
        if(instance)
        {
            throw error("Nesting of VKTestContext is not supported");
        }
        instance = this;
    }

    public void dispose()
    {
        instance = null;
    }

    static public VKTestContext current()
    {
        return instance;
    }
}
The class that consumes context:
class VKTestExecutable
{
    void performAction()
    {
        VKTestContext context = VKTestContext::current();
        if (context && context.boolProperty)
        {
            info("True");
        }
        else
        {
            info("False");
        }
    }
}
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern
Alternative: Singleton pattern


 

Search

About

DaxOnline.org is free platform that allows you to quickly store and reuse snippets, notes, articles related to Dynamics AX.

Authors are allowed to set their own AdSense units.
Join us.

Blog Tags