Castle Windsor解决了一个通用接口

时间:2012-10-29 11:04:19

标签: c# generics castle-windsor

我有一些实现的通用接口。

interface IBaseInterface<in TObject, out TDetails>
{
    TDetails GetDetails(TObject obj);
}

abstract class BaseImpl<TObject> : IBaseInterface<TObject, string>
{
    public abstract string GetDetails(TObject obj);
}

class Impl0 : BaseImpl<decimal>
{
    public override string GetDetails(decimal obj)
    {
        return "decimal";
    }
}

class Impl1 : BaseImpl<string>
{
    public override string GetDetails(string obj)
    {
        return "string";
    }
}

class Impl2 : BaseImpl<Details>
{
    public override string GetDetails(Details obj)
    {
        return "Details";
    }
}

class Impl3<TDetail> : BaseImpl<DetailsGeneric<TDetail>> where TDetail : Details
{
    public override string GetDetails(DetailsGeneric<TDetail> obj)
    {
        return "GenericDetails";
    }
}

class Details
{

}

class Details1 : Details
{

}

class DetailsGeneric<TDetails> : Details
{

}

将WinsdorInstaller类用于寄存器组件

container.Register(AllTypes.From(typeof(Program).Assembly.GetTypes())
  .BasedOn(typeof(IBaseInterface<,>)).WithServiceAllInterfaces()
  .LifestyleTransient());

尝试解决。最后两个调用抛出异常,但我希望它们返回为基类型声明的组件

class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer();

        container.Install(new WindsorInstaller());

        Details("test", container);

        Details(123m, container);

        Details(new Details(), container);

        Details(new DetailsGeneric<Details>(), container);

        Details(new Details1(), container); // "ComponentNotFound" exception

        Details(new DetailsGeneric<Details1>(), container); // "ComponentNotFound" exception           
    }

    static void Details<TType>(TType obj, WindsorContainer container)
    {
        var details = container.Resolve<IBaseInterface<TType, string>>().GetDetails(obj);

        Console.WriteLine(details);
    }
}

我哪里错了?我可以解决它吗?

1 个答案:

答案 0 :(得分:0)

您从我所看到的内容Details1上没有关闭任何组件......