Castle Windsor中的interface <t>绑定</t>

时间:2009-05-22 12:23:17

标签: dependency-injection castle-windsor

我有一个共同的datacontainer 接口IDataContainer

我将它用于不同类型的T. IPerson,ISuperMan等

在城堡里,我用

注册它
container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);

在运行时城堡用例如。

创建依赖
IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();

但它失败了,无法转换......类实现了接口,命名空间也是正确的等等。

电话

IPerson test = container.GetService<IPerson>();

作品(注册<IPerson,Person>

Cant castle解析interface<T>或?

2 个答案:

答案 0 :(得分:2)

所以这已经很晚了,但我想我知道你在这里要做什么。我能够通过这个:

IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();

通过注册这样的组件:

public class IoC
{
    public static void SetUp()
    {
        container = new WindsorContainer();
        container.AddComponent<IPerson, Person>();
        //container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
        //container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);
        container.AddComponentWithLifestyle("DataContainers", typeof(IDataContainer<>), typeof(DataContainer<>), LifestyleType.Transient);
    }

    public void TestOne()
    {
        SetUp();
        var test = container.GetService<IDataContainer<IPerson>>();
        Assert.That(test, Is.Not.Null);
    }

    public void TestTwo()
    {
        SetUp();
        var test = container.GetService<IPerson>();
        Assert.That(test, Is.Not.Null);
    }
}

internal interface IDataContainer<T> { }
internal class DataContainer<T> : IDataContainer<T> { }

internal interface IPerson { }
class Person : IPerson { }

internal interface ISuperMan { }
class SuperMan : ISuperMan { }

注释掉的两行是问题中存在的两行。

答案 1 :(得分:0)

这与温莎无关。由于C#2.0和3.0不支持泛型协方差,因此会出现转换错误。您可能正在DataContainer<T>实施IDataContainer<T>,这意味着DataContainer<Person>实施IDataContainer<Person>而不是IDataContainer<IPerson>这是您从容器中请求的内容。< / p>