C# Neo4JClient 有 GraphClient
,您必须在其中调用 .Connect()
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
在我见过的所有示例中,它都在控制台应用程序中,因此他们在 Main()
中声明了 GraphClient
并重新使用它。并且文档提到了它的线程安全性以及每个数据库只有一个实例并且不会多次调用 .Connect()
。
但是在 ASP.NET 应用程序中呢?我应该将它粘贴在页面访问的某个静态类中(或将其存储在应用程序状态中)吗?像这样:
public class DbConnection
{
private static GraphClient _client;
public static GraphClient GraphClient
{
get
{
if (_client == null)
{
_client = new GraphClient(new Uri("http://localhost:7474/db/data"));
_client.Connect();
}
return _client;
}
}
}
然后在任何 ASPX 页面中我可以简单地:
protected void Page_Load(object sender, EventArgs e)
{
GraphClient client = DbConnection.GraphClient;
//do whatever I need to with client
}
还是我理解不正确,会导致各种问题?我是否需要在每个方法中调用 .Connect()
(或者每个页面生命周期一次),如下所示:
private GraphClient _client;
private GraphClient PageGraphClient
{
get { //same as in previous, check if null and load _client with the connection }
}
protected void Page_Load(object sender, EventArgs e)
{
//do whatever I need to with PageGraphClient
}
protected void btnSave_Click(object sender, EventArgs e)
{
//do whatever I need to with PageGraphClient
}
等等?我想我只是对整个线程安全的事情和“与数据库建立了太多连接”挂断了电话,并想确保我没有错过一个简单/正确的方法来做到这一点。
(是的,我知道我不应该直接从 ASPX 页面调用数据库命令,为了理解 GraphClient 类的工作原理,我过度简化了;)
最佳答案
使用 Ninject(DI 框架)设置您的项目:
- 为您的 MVC 版本(即 Ninject.MVC5 等)添加 Ninject.MVC nuget 包
- 添加 Neo4jClient 包(尽管我想您已经有了)
- 连接 Ninject,让它知道什么是
IGraphClient
我为此使用了一个模块,所以将这个类添加到您的项目中(通常我将它们放在 App_Start 文件夹中名为“Modules”的子文件夹中——但它可以在任何地方):
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;
}
}
我们已将 GraphClient 加载到单例范围中,您可以在此处阅读所有相关信息:Object Scopes
现在我们只需要告诉 Ninject 加载模块,所以在 NinjectWebCommon.cs
文件(在 App_Start 文件夹中)编辑 RegisterServices
方法(在底部的文件)所以它看起来像:
/// <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) Controller
这是添加构造函数(或修改现有构造函数)以采用 IGraphClient
实例的情况:
private readonly IGraphClient _graphClient;
public HomeController(IGraphClient graphClient)
{
_graphClient = graphClient;
}
现在 Controller 有一个 GraphClient
的实例可以随时使用:
public ActionResult Index()
{
ViewBag.NodeCount = _graphClient.Cypher.Match("n").Return(n => n.Count()).Results.Single();
return View();
}
显然扩展它,您可以添加一个基础 Neo4jController
,任何需要 Neo4j 的 Controller 都会覆盖它。
关于c# - ASP.NET 和 Neo4jClient - 在哪里存储连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22703154/