Skip to content

Instantly share code, notes, and snippets.

@MilanLund
Last active September 13, 2024 10:57
Show Gist options
  • Save MilanLund/16c26046b2fa0ed16970be617707b219 to your computer and use it in GitHub Desktop.
Save MilanLund/16c26046b2fa0ed16970be617707b219 to your computer and use it in GitHub Desktop.
Rebuild search index on application start in Xperience by Kentico
using CMS;
using CMS.Base;
using CMS.Core;
using CMS.DataEngine;
using Kentico.Xperience.Lucene.Core.Indexing;
[assembly: RegisterModule(typeof(RebuildIndexPostStartModule))]
public class RebuildIndexPostStartModule : Module
{
private ILuceneClient? luceneClient;
private IEventLogService? eventLogService;
public RebuildIndexPostStartModule()
: base("RebuildIndex")
{
}
protected override void OnInit()
{
base.OnInit();
luceneClient = Service.Resolve<ILuceneClient>();
eventLogService = Service.Resolve<IEventLogService>();
if (eventLogService != null)
{
eventLogService.LogInformation(nameof(RebuildIndexPostStartModule), nameof(OnInit), "RebuildIndexPostStartModule initialized");
}
ApplicationEvents.PostStart.Execute += (sender, e) => Task.Run(() => RebuildIndex());
}
private async Task RebuildIndex()
{
try
{
if (luceneClient != null)
{
await luceneClient.Rebuild(Constants.NewsSearchIndex, null);
}
if (eventLogService != null)
{
eventLogService.LogInformation(nameof(RebuildIndexPostStartModule), nameof(RebuildIndex), "RebuildIndexPostStartModule finished");
}
}
catch (Exception ex)
{
if (eventLogService != null)
{
eventLogService.LogException(nameof(RebuildIndexPostStartModule), nameof(RebuildIndex), ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment