Grasshopper.OpenDocument works from python, not from C#

Hello,

I’m writing a C# script that needs to run a grasshopper graph. It works when I manually open the grasshopper document before running the script, but I want to be able to open it automatically.
However, I’m getting weird error (“object not found”) when loading from C#. However it works from python script with the exact same code:

Python code:

import Rhino
#Load Grasshopper Plugin as gh
gh = Rhino.RhinoApp.GetPlugInObject(“Grasshopper”)
gh.OpenDocument(r"D:\Programming\ladybugtexture.ghx")

C# code (after including Grasshopper.dll as reference):

Grasshopper.Plugin.GH_RhinoScriptInterface grasshopper = (Grasshopper.Plugin.GH_RhinoScriptInterface)RhinoApp.GetPlugInObject(“Grasshopper”);
grasshopper.OpenDocument(@“D:\Programming\ladybugtexture.ghx”);
return Result.Success;

I get this in C#, but it works in python:
image

This is the graph I’m trying to load:
ladybugtexture.ghx (68.9 KB)

What could be the reason for the difference? Does the working directory (or anything of that kind) change while running a plugin?

Was able to answer my own problem. Explanation in the comment + solving code below:

    //Workaround: Grasshopper does not work correctly if the assembly is loaded by this plugin
    //Referenced assemblies are loaded in .Net when a function that uses the reference is invoked
    //Therefore, we use the "dynamic" mechanism to load Grasshopper (if needed) from the main Rhino assembly
    //in a separate function before calling a function that actually uses the reference.
    private void LoadGrasshopperIfNeeded()
    {   
        dynamic grasshopper = RhinoApp.GetPlugInObject("Grasshopper");
        if (!grasshopper.IsEditorLoaded())
        {
            grasshopper.LoadEditor();
        }
    }