如何在解析服务形式WindsorContainer时注入依赖项?

时间:2009-09-05 09:26:06

标签: c# castle-windsor

这是我的情景: 我有一个ISampleProvider接口:

public interface ISampleProvider<TEntity>
{
TEntity Entity{get;}
}

这是这个界面的实现:

public class SampleProvider<TEntity>:ISampleProvider<TEntity>
{
public SampleProvider(TEntity entity)
{
Entity=entity;
}
public TEntity Entity
{
get;private set;
}
}

当我从WindsorContainer解析它时,我想将一个实体注入SampleProvider 所以我写了这个:

var container=new WindsorContainer();
container.AddComponent("smaple_provider",typeof(ISampleProvider<Person>),typeof(SampleProvider<Person>));
var arguments=new Hashtable{{"entity",new Person()}};
var sampleProvider=container.Resolve<ISampleProvider<Person>>(arguments);

但它没有工作,抛出依赖解析器异常,说“在配置中检测到循环”

显然我做错了。

1 个答案:

答案 0 :(得分:2)

确保你有Windsor 2.0 ...... 这个测试对我来说很好:

[TestFixture]
public class SampleProviderTests {
    public interface ISampleProvider<TEntity> {
        TEntity Entity { get; }
    }

    public class SampleProvider<TEntity> : ISampleProvider<TEntity> {
        public SampleProvider(TEntity entity) {
            Entity = entity;
        }

        public TEntity Entity { get; private set; }
    }

    public class Person {}

    [Test]
    public void test() {
        var container = new WindsorContainer();
        container.AddComponent("smaple_provider", typeof(ISampleProvider<Person>), typeof(SampleProvider<Person>));
        var arguments = new Hashtable { { "entity", new Person() } };
        var sampleProvider = container.Resolve<ISampleProvider<Person>>(arguments);            
    }
}