使用基类和接口使用 Castle.Windsor 和约定注册组件

本文关键字:注册 组件 约定 接口 基类 Castle Windsor | 更新日期: 2023-09-27 18:35:39

我的解决方案中有组件,这些组件可以根据用户的不同状态处理系统中的重定向。这些组件基于抽象类型 RedirectAction 并正在执行工作。

我在系统中还有另一个界面,用于监视服务和功能是否正常工作/处于活动状态。称为IStatusCheck。

        container.Register(
            AllTypes.FromThisAssembly()
                .BasedOn<IStatusCheck>()
                .WithServiceBase()
                .LifestyleTransient());
        container.Register(
            AllTypes.FromThisAssembly()
                .BasedOn<RedirectAction>()
                .WithServiceBase()
                .LifestyleTransient());

这很好用,直到我让重定向操作实现IStatusCheck以启用对它们的监视。而且我不知道如何注册才能在两者中检索组件。

ResolveAll<RedirectAction>()
ResolveAll<IStatusCheck>()

请帮帮我。

编辑:

更完整的示例

class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer();
        container.Register(
            AllTypes.FromThisAssembly()
                .BasedOn<IGenericInterface>()
                .WithServiceBase()
                .AllowMultipleMatches());
        Debug.Assert(container.ResolveAll<IGenericInterface>().Count() == 2, "Could not find all IGenericInterface types");
        container.Register(
            AllTypes.FromThisAssembly()
                .BasedOn<SpecificAbstractBase>()
                .WithServices(typeof(SpecificAbstractBase))
                .AllowMultipleMatches());
        var specific = container.ResolveAll<IGenericInterface>().First() as SpecificAbstractBase;
        Debug.Assert(specific != null, "Instance was not of expected type");
        Debug.Assert(container.ResolveAll<IGenericInterface>().Count() == 2, "Could not find all IGenericInterface types");
        Debug.Assert(container.ResolveAll<SpecificAbstractBase>().Count() == 2, "Could not find all SpecificAbstractBase types");
    }
}
public interface IGenericInterface
{
    bool ImAlive { get; }
}
public abstract class SpecificAbstractBase : IGenericInterface
{
    public abstract void DoTheJob();
    public bool ImAlive
    {
        get { return true; }
    }
}
public class SpecificOne : SpecificAbstractBase
{
    public override void DoTheJob() { }
}
public class SpecificTwo : SpecificAbstractBase
{
    public override void DoTheJob() { }
}

使用基类和接口使用 Castle.Windsor 和约定注册组件

使用 .AllowMultipleMatches() 允许将类型用于多个组件。