vgquotes/Src/VideoGameQuotes.Web/Configuration/EnableSearchWithLucene.cs

76 lines
2.9 KiB
C#

using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Reflection;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Store;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using Portoa.Lucene;
using Portoa.Persistence;
using Portoa.Search;
using Portoa.Web.Unity;
using Portoa.Web.Unity.Lifetime;
using VideoGameQuotes.Api;
using VideoGameQuotes.Web.Search;
using Directory = Lucene.Net.Store.Directory;
using Version = Lucene.Net.Util.Version;
namespace VideoGameQuotes.Web.Configuration {
public class EnableSearchWithLucene : UnityContainerExtension {
protected override void Initialize() {
var indexWriterLifetimeManager = new ExplicitlyDisposableLifetimeManager<IndexWriter>(
new ContainerControlledLifetimeManager(),
indexWriter => indexWriter.Close()
);
Container
.RegisterType<Directory>(new ContainerControlledLifetimeManager(), new InjectionFactory(CreateIndexDirectory))
.RegisterType<IndexWriter>(indexWriterLifetimeManager, new InjectionFactory(CreateIndexWriter))
.RegisterInstance(Version.LUCENE_29)
.RegisterType<Analyzer, StandardAnalyzer>(new InjectionConstructor(typeof(Version)))
.RegisterType<QueryParser>(new InjectionFactory(CreateQueryParser))
.RegisterAndIntercept(typeof(ISearcher<>), typeof(LuceneEntitySearcher<>))
.RegisterAndIntercept(typeof(ISearchService<>), typeof(SearchService<>))
.RegisterAndIntercept<ILuceneDocumentHandler<Quote>, QuoteDocumentHandler>()
.RegisterAndIntercept(typeof(ISearchIndexBuilder<>), typeof(LuceneEntityIndexBuilder<>));
Container
.Configure<Interception>()
.AddPolicy("UpdateSearchIndexPolicy")
.AddCallHandler<UpdateSearchIndexCallHandler>()
.AddMatchingRule<QuoteUpdatedMatchingRule>();
}
#region lucene-related factories
private static QueryParser CreateQueryParser(IUnityContainer container) {
return new QueryParser(container.Resolve<Version>(), "text", container.Resolve<Analyzer>());
}
private static Directory CreateIndexDirectory(IUnityContainer container) {
var indexDirectory = ((NameValueCollection)ConfigurationManager.GetSection("vgquotes"))["luceneIndexDirectory"];
return new SimpleFSDirectory(new DirectoryInfo(indexDirectory));
}
private static IndexWriter CreateIndexWriter(IUnityContainer container) {
return new IndexWriter(
container.Resolve<Directory>(),
new StandardAnalyzer(Version.LUCENE_29),
true,
IndexWriter.MaxFieldLength.UNLIMITED
);
}
#endregion
public class QuoteUpdatedMatchingRule : IMatchingRule {
private static readonly MethodBase saveMethod = typeof(IRepository<Quote, int>).GetMethod("Save", new[] { typeof(Quote) });
public bool Matches(MethodBase member) {
return member == saveMethod;
}
}
}
}