Warm tip: This article is reproduced from serverfault.com, please click

How to handle the new ConnectAsync API (C# Neo4jClient)

发布于 2020-12-04 05:54:59

I updated the Neo4JClient to the version 4.x which included refactoring from client.Connect(); to client.ConnectAsync(). The controller which connects to neo4j is getting instantiated when a request to the api is made, so there is not much time between connecting and using the connection. The async connecting so my guess runs me in the problem, that the client is not connected when I'm already making database requests. I tried to fix this with awaiting the ResultsAsync which didn't fix the problem. Currently there is no documentation existing since it's outdated. Here is my Code :

        // The client is getting injected from my server
        public MyService(GraphClient client)
        {
            this.client = client;
            this.client.ConnectAsync();
        }

        public async Task<bool> Login(string username, string password)
        {
            var query = client.Cypher
                .Match("(n)")
                .Where("n.username = '" + username + "' AND n.password = '" + password + "'")
                .Return(n => n.As<User>());

            var queryResult = await query.ResultsAsync;
            return queryResult.ToList().Count == 1;
        }
Questioner
TobiasW
Viewed
0
Charlotte Skardon 2020-12-04 20:11:41

In your constructor, you would do:

var task = this.client.ConnectAsync();
task.Wait();

Or you can do:

this.client.ConnectAsync().Wait();

A couple of things extra, the GraphClient you are injecting should really be an IGraphClient - this will make it easier for you if you decide to change to a Bolt version later on.

The other, more important thing, is that the server injecting it, should have already done the ConnectAsync bit - you only want to call that once, and if it's injected into multiple classes, it'll be called more than once.