Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Provides a search context object based on the type of the search result model
var indexName = $"feature_{Sitecore.Context.Database.Name}_index";
using(var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
{
// execute search query
}
public interface ISearchContextFactory<T>
{
IProviderSearchContext GetSearchContext();
}
public interface ISearchContextProvider
{
IProviderSearchContext GetSearchContext<T>();
}
public abstract class MasterWebSearchContextFactory<T> : ISearchContextFactory<T>
{
private const string Master = "master";
protected abstract string MasterIndex { get; }
protected abstract string WebIndex { get; }
public virtual IProviderSearchContext GetSearchContext()
{
return GetSearchIndex().CreateSearchContext();
}
public virtual ISearchIndex GetSearchIndex()
{
var db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
var indexName = db != null && db.Name.Equals(Master, StringComparison.OrdinalIgnoreCase) ? MasterIndex : WebIndex;
return ContentSearchManager.GetIndex(indexName);
}
}
var indexable = new SitecoreIndexableItem(dataSourceItem);
using(var context = ContentSearchManager.CreateSearchContext(indexable)
{
// execute search query
}
public class SampleSearchContextFactory : MasterWebSearchContextFactory<SampleSearchResultItem>
{
protected override string MasterIndex => "sample_master_index";
protected override string WebIndex => "sample_web_index";
}
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<services>
<configurator type="SampleProject.SearchContextConfigurator, SampleProject" />
</services>
</sitecore>
</configuration>
public class SearchContextConfigurator : IServicesConfigurator
{
public void Configure(IServiceCollection serviceCollection)
{
serviceCollection.Scan(selector =>
{
selector.FromApplicationDependencies()
.AddClasses(classes => classes.AssignableTo(typeof(ISearchContextFactory<>)))
.AsImplementedInterfaces()
.WithSingletonLifetime();
});
serviceCollection.AddSingleton<ISearchContextProvider, ServiceLocatorSearchContextProvider>();
}
}
using (var context = _searchContextProvider.GetSearchContext<SampleSearchResultItem>())
{
// execute search query
}
public class ServiceLocatorSearchContextProvider : ISearchContextProvider
{
public IProviderSearchContext GetSearchContext<T>()
{
try
{
return ServiceLocator.ServiceProvider.GetService<ISearchContextFactory<T>>()?.GetSearchContext();
}
catch (Exception e)
{
Log.Error($"Could not create search context for search result type {typeof(T).Name}", e, this);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment