Castle 3.0如何移除组件
本文关键字:组件 何移 Castle | 更新日期: 2023-09-27 18:26:12
我有IWindsorContaner,它在整个应用程序生命周期中都存在。对于Unittest,可以在其Type下注册mock/stub等。当测试完成并处理夹具时,将使用名为"注销"的自行创建的方法删除测试中已注册的组件。
现在,我想更新到最新的Castle版本,它是3.0。根据3.0的发行说明,类似
public void Unregister(string contextName, string registrationName)
{
IWindsorContainer context = GetOrCreateContext(contextName);
context.Kernel.RemoveComponent(registrationName);
}
不再可能,因为IKernel.RemoveComponent方法已被删除。修复此问题的描述实际上并不充分("尝试使用IHandlerSelectors。")。
我用于单元测试的夹具的简化版本:
public sealed class DependencyInjectionFixture : IDisposable
{
private Stack<Type> registeredTypes = new Stack<Type>();
// Registering of mocks/stubs, etc
public void RegisterSingleton<T>(T singleton, string objectName)
{
registeredTypes.Push(typeof(T));
IWindsorContainer context = GetOrCreateContext(contextName);
context.Register(Component.For(typeof(T))
.Named(objectName)
.Instance(singleton)
.LifeStyle.Singleton);
}
// Called when tests ends
public void Dispose()
{
IWindsorContainer context = GetOrCreateContext(contextName);
while (registeredTypes.Count > 0)
context.Kernel.RemoveComponent(CSApplicationContext.GetRegistrationNameFor(registeredTypes.Pop()));
}
}
如何使用Castle 3.0删除组件?
不要试图删除所有组件,只需创建一个新的IWindsorContainer
并将其绑定到GetOrCreateContext
正在检查的任何组件。然后你会有一个新的容器,它没有任何绑定。
我知道我比赛迟到了,但我遇到了同样的问题。我的问题是,由于应用程序的规模,Castle Windsor的首次运行非常缓慢(1秒以上),为每次测试创建新的上下文变得越来越繁重(600次测试,仅在Castle WindWindsor上等待5分钟)
我的解决方案基于如何删除温莎城堡3.0中的组件?
public class WindsorHandlerOverride : IHandlerSelector
{
private Dictionary<Type, object> definedTypeBehaviours;
public bool HasOpinionAbout(string key, Type service)
{
return definedTypeBehaviours.IsNotNullAndAny(t => t.Key == service);
}
public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
{
var theValue = definedTypeBehaviours[service];
return new WindsorSimpleHandler {TheValue = theValue};
}
public void CleanUp()
{
definedTypeBehaviours = null;
}
public void OverrideBehaviour(Type type, object value)
{
if (definedTypeBehaviours == null)
{
definedTypeBehaviours = new Dictionary<Type, object>();
}
definedTypeBehaviours.Add(type, value);
}
}
和
public class WindsorSimpleHandler : IHandler
{
public object TheValue { get; set; }
public ComponentModel ComponentModel { get; set; }
public HandlerState CurrentState { get; set; }
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
return true;
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
return TheValue;
}
public object Resolve(CreationContext context)
{
return TheValue;
}...
然后无论你在哪里设置windsor
WindsorOverrider = new WindsorHandlerOverride();
container.Kernel.AddHandlerSelector(WindsorOverrider);
当你想在测试中覆盖城堡风或默认行为时
WindsorOverrider.OverrideBehaviour(typeof(IService), mock.Object);
在测试拆卸时呼叫
WindsorOverrider.CleanUp();