Typical usage of search api uses a using statement to dispose of the search context.
using (var context = ContentSearchManager.GetIndex(_indexName).CreateSearchContext())
{
var hits = context.GetQueryable<SearchResult>();
return hits;
}
This runs into a problem with hits.result or lucene reader being disposed before it can be used by the calling method. This may be more likely if creating a search service rather than calling this (for example) within an MVC controller.
Often this disposal problem is addressed by calling ToList() creating an IEnumerable<SearchResult>
and returning that instead.
return hits.ToList()
By doing this, we loose hits.GetResults() and the properties within - Hits
, TotalSearchResults
and Facets
An alternative approach mentioned is to use a single search context that is not disposed and instead reused across the application.
Question
- Is using a single, reused context a good approach?
- Are there any pitfalls?
- Are there any good code examples of doing this, possibly with a dependency injection framework handling a singleton.