ASP.NET和Neo4jClient-存储连接的位置
本文关键字:连接 位置 存储 Neo4jClient- NET ASP | 更新日期: 2023-09-27 17:54:30
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.MVC nuget包(即Ninject.MVC5等(
- 添加Neo4jClient包(尽管我想你已经有了(
- 连接Ninject,让它知道什么是
IGraphClient
我使用了一个模块,所以把这个类添加到你的项目中(通常我把它们放在App_Start文件夹中一个名为"模块"的子文件夹中,但它可以在任何地方(:
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,您可以在这里阅读它的全部内容:对象作用域
现在我们只需要告诉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>();
}
- 注入控制器
这是一种添加构造函数(或修改现有构造函数(以获取IGraphClient
实例的情况:
private readonly IGraphClient _graphClient;
public HomeController(IGraphClient graphClient)
{
_graphClient = graphClient;
}
现在,控制器有一个GraphClient
的实例,可以随时使用:
public ActionResult Index()
{
ViewBag.NodeCount = _graphClient.Cypher.Match("n").Return(n => n.Count()).Results.Single();
return View();
}
显然,扩展了这一点,您可以添加一个基础Neo4jController
,任何需要Neo4j的控制器都可以覆盖它。