有没有安全的方法来解决Castle.Windsor中的组件?

时间:2016-05-04 16:47:53

标签: c# dependency-injection asp.net-mvc-5 castle-windsor

我有我的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);
        }
    }
}

它有效,但我真的想避免异常

1 个答案:

答案 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