To set up your project with Ninject (DI framework):
- Add the Ninject.MVC nuget package for your MVC version (i.e. Ninject.MVC5 etc)
- Add the Neo4jClient package (though I imagine you already have this)
- Hook up Ninject so it knows what an
IGraphClient
is
I use a Module for this, so add this class to your project (usually I have them in a sub-folder called ‘Modules’ in the App_Start folder – but it can be anywhere):
public class Neo4jModule : NinjectModule
{
/// <summary>Loads the module into the kernel.</summary>
public override void Load()
{
Bind<IGraphClient>().ToMethod(InitNeo4JClient).InSingletonScope();
}
private static IGraphClient InitNeo4JClient(IContext context)
{
var neo4JUri = new Uri(ConfigurationManager.ConnectionStrings["Neo4j"].ConnectionString);
var graphClient = new GraphClient(neo4JUri);
graphClient.Connect();
return graphClient;
}
}
We've loaded the GraphClient in a singleton scope which you can read all about here: Object Scopes
Now we just need to tell Ninject to load the module, so in the NinjectWebCommon.cs
file (in the App_Start folder) edit the RegisterServices
method (at the bottom of the file) so it looks like:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Load<Neo4jModule>();
}
- Inject into the controller
Which is a case of adding a constructor (or modifying an existing one) to take an IGraphClient
instance:
private readonly IGraphClient _graphClient;
public HomeController(IGraphClient graphClient)
{
_graphClient = graphClient;
}
Now the controller has an instance of the GraphClient
to use as and when it pleases:
public ActionResult Index()
{
ViewBag.NodeCount = _graphClient.Cypher.Match("n").Return(n => n.Count()).Results.Single();
return View();
}
Obviously extending this, you could add a base Neo4jController
which any controllers requiring Neo4j override.