Skip to content

Instantly share code, notes, and snippets.

@mookid8000
Created April 20, 2012 10:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mookid8000/2427676 to your computer and use it in GitHub Desktop.
Save mookid8000/2427676 to your computer and use it in GitHub Desktop.
MongoInstaller
namespace Web.Installers
{
public class MongoInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container
.Register(AllTypes.FromThisAssembly()
.BasedOn<IIndexCreationTask>()
.WithService.Base(),
Component.For<MongoServer>()
.UsingFactoryMethod(k => MongoServer.Create(MongoUri()))
.OnCreate((k, s) => s.Connect())
.LifeStyle.Singleton,
Component.For<MongoDatabase>().UsingFactoryMethod(GetMongoDatabase),
Component.For<ILazyComponentLoader>()
.ImplementedBy<MongoCollectionComponentLoader>()
.LifeStyle.Singleton);
}
Uri MongoUri()
{
return new Uri(ConfigurationManager.AppSettings["MONGOHQ_URL"]);
}
MongoDatabase GetMongoDatabase(IKernel kernel)
{
return kernel.Resolve<MongoServer>().GetDatabase(MongoUri().LocalPath.TrimStart('/'));
}
}
public class MongoCollectionComponentLoader : ILazyComponentLoader
{
readonly ConcurrentDictionary<Type, MethodInfo> factoryMethodCache = new ConcurrentDictionary<Type, MethodInfo>();
public IRegistration Load(string key, Type service, IDictionary arguments)
{
var requestedServiceIsMongoCollection = service.IsGenericType
&& service.GetGenericTypeDefinition() == typeof (MongoCollection<>);
if (!requestedServiceIsMongoCollection)
return null;
return Component.For(service).UsingFactoryMethod(k => ResolveCollection(k, service));
}
object ResolveCollection(IKernel kernel, Type service)
{
var documentType = service.GetGenericArguments().Single();
var mongoDatabase = kernel.Resolve<MongoDatabase>();
var collectionMethodInfo = GetCollectionGetter(mongoDatabase, documentType);
return collectionMethodInfo.Invoke(mongoDatabase, new object[] {documentType.Name});
}
MethodInfo GetCollectionGetter(MongoDatabase mongoDatabase, Type documentType)
{
MethodInfo methodInfoToReturn;
if (!factoryMethodCache.TryGetValue(documentType, out methodInfoToReturn))
{
methodInfoToReturn = mongoDatabase.GetType()
.GetMethods()
.Single(m => m.Name == "GetCollection"
&& m.IsGenericMethod
&& m.GetParameters().Length == 1
&& m.GetParameters().Single().ParameterType == typeof (string))
.MakeGenericMethod(documentType);
factoryMethodCache.TryAdd(documentType, methodInfoToReturn);
}
return methodInfoToReturn;
}
}
}
@anhle128
Copy link

anhle128 commented Dec 9, 2015

Can you show to me a demo about how to use this MongoInstaller ?
Thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment