我有我的ControllerFactory实现来处理控制器中的构造函数注入,但是我想使用默认方式解析控制器,以防其中一些未注册:
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IWindsorContainer _container;
public WindsorControllerFactory(IWindsorContainer container)
{
_container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType != null)
{
try
{
return _container.Resolve(controllerType) as IController;
}
catch(Exception ex)
{
return base.GetControllerInstance(requestContext, controllerType);
}
}
else
{
return base.GetControllerInstance(requestContext, controllerType);
}
}
}
它有效,但我真的想避免异常
答案 0 :(得分:2)
使用container.Kernel.HasComponent(Type type)
:
bool isRegistered;
var container = new WindsorContainer();
isRegistered = container.Kernel.HasComponent(typeof(IFoo));
Console.WriteLine(isRegistered);
container.Register(Component.For<IFoo>().ImplementedBy<Foo>());
isRegistered = container.Kernel.HasComponent(typeof(IFoo));
Console.WriteLine(isRegistered);
输出:
False
True