Search code examples
c#neo4jneo4j-bolt

Where/when is the place to call Dispose() on a Neo4j IDriver?


I am creating nodes and relationships from a c# service and I am not sure when the ideal time to call dispose would be. I have three methods that create Neo4j nodes and two that create relationships. These are called right after the other. Each method creates a new driver. (Is it best to not create a new driver in each method?)

createNodes1();
createNodes2();
createNodes3();

createRelationships1();
createRelationships2();

Each method generically looks like the code excerpt below.

internal void addNode(string nodeName, string nodeLabel)
{
    IDriver driver = GraphDatabase.Driver("bolt://localhost:11004", AuthTokens.Basic("neo4j", "Diego123"));
    using (ISession session = driver.Session())
    {
        IStatementResult result = session.Run("CREATE (n:" + nodeLabel + "{name:'" + nodeName + "'})");             
    }
    driver.Dispose();
}

(Calling Dispose() at the end of each method gives an error, so my desire is not to place it there. I am just showing what I had initially and requesting advice on where the best place to put it would be.)


Solution

  • Any object that implements IDisposable can be instantiated with a using statement, and at the end of that block, the object will be disposed (you're already doing this with session), so there's no need to explicitly call it.

    See Using objects that implement IDisposable for more info.

    using (IDriver driver = GraphDatabase.Driver("bolt://localhost:11004", 
        AuthTokens.Basic("neo4j", "Diego123")))
    {
        using (ISession session = driver.Session())
        {
            IStatementResult result = session.Run("CREATE (n:" + nodeLabel + 
                "{name:'" + nodeName + "'})");             
        }
    }