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

71 lines
2.9 KiB
C#
Raw Normal View History

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(new 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>(), container.Resolve<Analyzer>(), true, IndexWriter.MaxFieldLength.UNLIMITED);
}
#endregion
private 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;
}
}
}
}