在 Castle Windsor 多次注册

Multiple registrations with Castle Windsor

我在 WPF 应用程序中遇到以下情况:

public class ExpenseView : UserControl, IAccountingView {}

// just a marker, the contract is in IViewWindow
public interface IAccountingView : IViewWindow {}

我需要能够注册 ExpenseView 以通过两种方式解析,作为具体类型,ExpenseView 和作为 IAccountingView(也可能作为另一个接口)。

我正在注册这样的类型:

// I need a collection of IViewWindow to be used
Container.Register( Classes.FromAssemblyInDirectory( myTypes )
    .BasedOn<IViewWindow>()
    .WithServiceFromInterface()
    .LifestyleTransient()
    );

// all other types don't have interfaces, are used as concrete types.
Container.Register( Classes.FromAssemblyInDirectory( myTypes )
    .Where( type => type.IsPublic )
    .WithServiceSelf()
    .LifestyleTransient()
    );

现在,这有效,ExpenseView 和所有其他类型都已实例化,除了当我需要使用时

var newInstance = container.Resolve( iView.ViewType );

获取另一个实例,其中 iView.ViewType 是具体类型 ExpenseView(根据示例),我得到此异常:

'Castle.MicroKernel.ComponentNotFoundException'  
No component for supporting the service ExpenseView was found.

知道为什么会发生这种情况以及如何让它发挥作用吗?

这里对各种注册选项有很好的解释:http://docs.castleproject.org/Windsor.Registering-components-by-conventions.ashx

要注册所有 IViewWindow 实现者以及它们的具体类型,您可以这样做:

Container.Register( Classes.FromAssemblyInDirectory( myTypes )
    .BasedOn<IViewWindow>()
    .WithServiceFromInterface()
    .WithServiceSelf()
    .LifestyleTransient()
    );