代码之家  ›  专栏  ›  技术社区  ›  driis

Castle Windsor:配置通用服务并提供非通用实现失败

  •  0
  • driis  · 技术社区  · 15 年前

    使用castle windsor,我想用类型参数配置一个通用服务;并让它由一个已知的具体类型实现,该类型使用一个特定类型作为通用参数来实现该服务。作为一个单元测试,我想让以下内容发挥作用:

    [TestClass]
    public class WindsorTests
    {
        [TestMethod]
        public void ResolveGenericEntity_Test()
        {
            WindsorContainer container = ConfigureContainer();
            IEntity<string> entity = container.Resolve<IEntity<string>>();
            Assert.IsNotNull(entity);
        }
    
        private WindsorContainer ConfigureContainer()
        {
            WindsorContainer container = new WindsorContainer();
            container.AddComponent("entity", typeof(IEntity<>), typeof(ConcreteEntity));
            return container;
        }
    }
    
    public interface IEntity<T> { }
    
    public class ConcreteEntity : IEntity<string> {}
    

    此测试失败,出现以下异常:

    System.InvalidOperationException:无效操作异常: windsorgenericstest.concreteEntity是 不是泛型类型定义。 只能对调用MakeGenericType 一种类型 type.IsGenerictypedefinition为true。

    现在,我发现了 post here 描述相同的问题。海报描述了如何通过更改defaultgenerichandler.resolvecore方法来解决这一问题。但是,我不想更改城堡代码本身并在自定义构建上运行。

    有人知道我如何在不修改城堡温莎源代码的情况下解决这个问题吗?如果需要的话,我很高兴能够实现一个设施来支持这一点。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Daniel Plaisted    15 年前

    如果您将configureContainer中的行更改为这个行,它会工作吗?

    container.AddComponent("entity", typeof(IEntity<string>), typeof(ConcreteEntity));