0

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

Diego
  • 117
  • 11

2 Answers2

0

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 + "'})");             
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

Consider creating your connection (driver) and passing it into your class that contains your data manipulation methods (creating nodes, creating relationships, etc.) as a dependency.

If everything is in a single class here, you can make that class IDisposable and create the driver in its constructor, and call the driver Dispose method as part of your classes Dispose method.

You can dispose the driver and connection once you're finished doing all the work you're doing on the Neo4J DB for the given service request.

JustinW
  • 271
  • 1
  • 6