6

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.
6

Is using a single, reused context a good approach?

Yes. It is the recommended approach.

Are there any pitfalls?

Yes. New documents added to your indexes will not show, until you re-open a new Search Context. So you may need to tie in your SearchContext to index update events.

Are there any good code examples of doing this, possibly with a dependency injection framework handling a singleton.

Because of the pitfalls, setting this up in a DI Singleton is probably not a good idea. For an on-source reference and explanation, see Sitecore 7 Patterns for Global Search Context Reuse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.