CollectionsMetaHandler
using Castle.Core;
using Castle.Core.Internal;
using Castle.MicroKernel.ComponentActivator;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Castle.MicroKernel.Handlers
{
public class CollectionsMetaHandler : IMetaHandler, IDisposable
{
private static readonly MethodInfo buildHandlerGeneric = typeof(CollectionsMetaHandler).GetMethod("BuildHandlerGeneric", BindingFlags.Static | BindingFlags.NonPublic);
private readonly SimpleThreadSafeDictionary<Type, IHandler> innerHandlers = new SimpleThreadSafeDictionary<Type, IHandler>();
private IKernelInternal kernel;
public void Dispose()
{
innerHandlers.Dispose();
}
public IHandler GetHandler(Type service, IHandler[] existingHandlers)
{
if (existingHandlers.Length > 0)
return null;
Type compatibleArrayItemType = service.GetCompatibleArrayItemType();
if ((object)compatibleArrayItemType == null)
return null;
return innerHandlers.GetOrAdd(compatibleArrayItemType, BuildHandler);
}
public void Init(IKernelInternal kernel)
{
this.kernel = kernel;
}
private IHandler BuildHandler(Type type)
{
return (IHandler)buildHandlerGeneric.MakeGenericMethod(type).Invoke(this, null);
}
private IHandler BuildHandlerGeneric<T>()
{
ComponentModel componentModel = kernel.ComponentModelBuilder.BuildModel(new ComponentName("castle.auto-collection: " + typeof(T).ToCSharpString(), false), new Type[4] {
typeof(IEnumerable<T>),
typeof(ICollection<T>),
typeof(IList<T>),
typeof(T[])
}, typeof(T[]), null);
if (componentModel.LifestyleType == LifestyleType.Undefined)
componentModel.LifestyleType = LifestyleType.Transient;
if ((object)componentModel.CustomLifestyle == null)
componentModel.CustomComponentActivator = typeof(CollectionActivator<T>);
IKernelInternal kernelInternal = kernel;
bool isMetaHandler = true;
return kernelInternal.AddCustomComponent(componentModel, isMetaHandler);
}
}
}