使用SolrNet从控制台应用程序查询Solr?

Mun*_*Mun 1 solr linqpad solrnet

我正在尝试在命令行应用程序(或更准确地说,从LINQPad)中使用SolrNet来测试一些查询,并且在尝试初始化库时,我收到以下错误:

Key 'SolrNet.Impl.SolrConnection.UserQuery+Resource.SolrNet.Impl.SolrConnection' already registered in container
Run Code Online (Sandbox Code Playgroud)

但是,如果我捕获此错误并继续,ServiceLocator会给我以下错误:

Activation error occured while trying to get instance of type ISolrOperations`1, key ""
Run Code Online (Sandbox Code Playgroud)

内部异常:

The given key was not present in the dictionary.
Run Code Online (Sandbox Code Playgroud)

我的完整代码如下所示:

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"));
Run Code Online (Sandbox Code Playgroud)

我在安装了Solr 3.4.0的Windows 7x64上运行Tomcat 7.

还有另一条关于 StackOverflow上同样问题的消息,尽管在Global.asax中放置Startup.Init代码的公认答案仅与ASP.NET有关.

重新启动Tomcat7服务可以解决问题,但在每次查询后都必须这样做很麻烦.

使用SolrNet库从C#控制台应用程序与Solr交互的正确方法是什么?

Pai*_*ook 5

在控制台应用程序中使用SolrNet的正确方法是仅执行该行

 Startup.Init<Resource>("http://localhost:8080/solr/");
Run Code Online (Sandbox Code Playgroud)

一次用于控制台应用程序的生命周期.我通常把它作为我的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"));
}
Run Code Online (Sandbox Code Playgroud)

您的错误来自于您尝试多次初始化SolrNet连接的事实.您只需在控制台应用程序启动时初始化它一次,然后在需要时通过ServiceLocator引用(查找).

  • 看一下LINQPad设置,我认为你对多次初始化的SolrNet连接是正确的.看起来应用程序域被重用,这导致了这一点.进入首选项 - >高级并将"始终使用新应用程序域"设置为true似乎已解决问题(需要重新启动LINQPad).谢谢你的帮助. (5认同)