ComponentReference<T>
Reference to component obtained from a container.
using Castle.Core;
using Castle.MicroKernel.Context;
using System;
namespace Castle.MicroKernel
{
public class ComponentReference<T> : IReference<T>
{
private readonly Type actualComponentType;
private readonly string componentKey;
private DependencyModel dependency;
public ComponentReference(string componentKey)
{
if (componentKey == null)
throw new ArgumentNullException("componentKey");
this.componentKey = componentKey;
dependency = new DependencyModel(DependencyType.ServiceOverride, componentKey, null, false);
}
public ComponentReference(Type actualComponentType)
{
if ((object)actualComponentType == null)
throw new ArgumentNullException("actualComponentType");
this.actualComponentType = actualComponentType;
dependency = new DependencyModel(DependencyType.Service, null, actualComponentType, false);
}
public ComponentReference()
: this(typeof(T))
{
}
private IHandler GetHandler(IKernel kernel)
{
if (componentKey != null)
return kernel.GetHandler(componentKey);
return kernel.GetHandler(actualComponentType);
}
public T Resolve(IKernel kernel, CreationContext context)
{
IHandler handler = GetHandler(kernel);
if (handler != null)
try {
return (T)handler.Resolve(context);
} catch (InvalidCastException innerException) {
throw new Exception($"""{componentKey}""{typeof(T)}""", innerException);
}
throw new Exception($"""{componentKey ?? actualComponentType.ToString()}""");
}
public void Attach(DependencyModelCollection dependencies)
{
dependencies.Add(dependency);
}
public void Detach(DependencyModelCollection dependencies)
{
dependencies.Remove(dependency);
}
}
}