ComponentReference<T>
Reference to component obtained from a container.
using Castle.Core;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Util;
using System;
namespace Castle.MicroKernel
{
public class ComponentReference<T> : IReference<T>
{
private readonly DependencyModel dependency;
private readonly object value;
private Type ActualComponentType => value as Type;
private string ServiceOverrideComponentName => value as string;
public ComponentReference(string dependencyName, string componentName)
{
if (dependencyName == null)
throw new ArgumentNullException("dependencyName");
if (componentName == null)
throw new ArgumentNullException("componentName");
value = componentName;
dependency = new DependencyModel(dependencyName, typeof(T), false);
}
public ComponentReference(string dependencyName, Type actualComponentType)
{
if (actualComponentType == (Type)null)
throw new ArgumentNullException("actualComponentType");
value = actualComponentType;
dependency = new DependencyModel(dependencyName, actualComponentType, false);
}
public ComponentReference(string dependencyName)
: this(dependencyName, typeof(T))
{
}
public void Attach(ComponentModel component)
{
string text = ReferenceExpressionUtil.BuildReference(ServiceOverrideComponentName ?? ActualComponentType.FullName);
component.Parameters.Add(dependency.DependencyKey, text);
component.Dependencies.Add(dependency);
}
public void Detach(ComponentModel component)
{
component.Dependencies.Remove(dependency);
}
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 ComponentResolutionException($"""{ServiceOverrideComponentName}""{typeof(T)}""", innerException);
}
throw new ComponentResolutionException($"""{ServiceOverrideComponentName ?? ActualComponentType.ToString()}""");
}
private IHandler GetHandler(IKernel kernel)
{
if (ServiceOverrideComponentName != null)
return kernel.GetHandler(ServiceOverrideComponentName);
return kernel.GetHandler(ActualComponentType);
}
}
}