我试图在命令行应用程序(或更准确地说,从 LINQPad)中使用 SolrNet 来测试一些查询,并且在尝试初始化库时,我收到以下错误:
Key 'SolrNet.Impl.SolrConnection.UserQuery+Resource.SolrNet.Impl.SolrConnection' already registered in container
但是,如果我发现这个错误并继续,ServiceLocator 会给我以下错误:
Activation error occured while trying to get instance of type ISolrOperations`1, key ""
内部异常:
The given key was not present in the dictionary.
我的完整代码如下所示:
try
{
Startup.Init<Resource>("http://localhost:8080/solr/");
Console.WriteLine("Initialized\n");
}
catch (Exception ex)
{
Console.WriteLine("Already Initialized: " + ex.Message);
}
// This line causes the error if Solr is already initialized
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Resource>>();
// Do the search
var results = solr.Query(new SolrQuery("title:test"));
我在安装了 Solr 3.4.0 的 Windows 7x64 上运行 Tomcat 7。
有 another message about the same problem在 StackOverflow 上,尽管将 Startup.Init 代码放入 Global.asax 的公认答案仅与 ASP.NET 相关。
重新启动 Tomcat7 服务可以解决问题,但每次查询后都必须这样做很痛苦。
使用 SolrNet 库从 C# 控制台应用程序与 Solr 交互的正确方法是什么?
最佳答案
在控制台应用程序中使用 SolrNet 的正确方法是只执行该行
Startup.Init<Resource>("http://localhost:8080/solr/");
在您的控制台应用程序的生命周期内一次。我通常将其作为我的 Main 方法的第一行,如下所示...
static void Main(string[] args)
{
Startup.Init<Resource>("http://localhost:8080/solr/");
//Call method or do work to query from solr here...
//Using your code in a method...
QuerySolr();
}
private static void QuerySolr()
{
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Resource>>();
// Do the search
var results = solr.Query(new SolrQuery("title:test"));
}
您的错误来自您尝试多次初始化 SolrNet 连接这一事实。只需在控制台应用程序启动时初始化一次,然后在需要时通过 ServiceLocator 引用(查找)。
关于solr - 使用 SolrNet 从控制台应用程序查询 Solr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9397893/