solrlinqpadsolrnet

Using SolrNet to query Solr from a console application?


I'm trying to use SolrNet in a command line application (or more accurately, from LINQPad) to test some queries, and when trying to initialize the library, I get the following error:

Key 'SolrNet.Impl.SolrConnection.UserQuery+Resource.SolrNet.Impl.SolrConnection' already registered in container

However, if I catch this error and continue, the ServiceLocator gives me the following error:

Activation error occured while trying to get instance of type ISolrOperations`1, key ""

With the inner exception:

The given key was not present in the dictionary.

My full code looks like this:

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"));

I'm running Tomcat 7 on Windows 7x64 with Solr 3.4.0 installed.

Stack Overflow has another question about the same problem, though the accepted answer of putting the Startup.Init code in Global.asax is only relevant to ASP.NET.

Restarting the Tomcat7 service resolves the problem, but having to do this after every query is a pain.

What is the correct way to use the SolrNet library to interact with Solr from a C# console application?


Solution

  • The correct way to use SolrNet in a console application is to only execute the line

    Startup.Init<Resource>("http://localhost:8080/solr/");
    

    once for the life of your console application. I typically put it as the first line in my Main method as shown below...

    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"));
    }
    

    Your error is coming from the fact that you are trying to initialize the SolrNet connection multiple times. You only need to initialize it once when the console application starts and then reference (look up) via the ServiceLocator when needed.