Question

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.

There's another message about the same problem on StackOverflow, 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?

Was it helpful?

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.

OTHER TIPS

My Solution is clear Startup before Init

Startup.Container.Clear();
Startup.InitContainer();
Startup.Init<Resource>("http://localhost:8080/solr/");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top