代码之家  ›  专栏  ›  技术社区  ›  Aaron Fischer

用castle windsor中的泛型参数解析泛型

  •  0
  • Aaron Fischer  · 技术社区  · 14 年前

    我正在尝试注册一个类似iRequestHandler的类型 1[GenericTestRequest 1[t]]它将由GenericTestRequestHandler实现,但我当前从windsor“castle.microkernel.componentNotFoundException:No component for supporting the service”获取错误。是否支持此类型的操作?或者它是否远离支持的寄存器(component.for(typeof(ilist<>).implementedby(typeof(list<>))

    下面是一个断裂测试的例子。 //////////////////////////////////////////////////////

    public interface IRequestHandler{}
    
    public interface IRequestHandler<TRequest> : IRequestHandler where TRequest : Request{} 
    
    public class  GenericTestRequest<T> : Request{} 
    
    public class GenericTestRequestHandler<T> : RequestHandler<GenericTestRequest<T>>{}
    
    [TestFixture]
    public class ComponentRegistrationTests{
       [Test]
       public void DoNotAutoRegisterGenericRequestHandler(){
    
    var IOC = new Castle.Windsor.WindsorContainer();
    var type = typeof( IRequestHandler<> ).MakeGenericType( typeof( GenericTestRequest<> ) );
    IOC.Register( Component.For( type ).ImplementedBy( typeof( GenericTestRequestHandler<> ) ) );
    
    var requestHandler = IoC.Container.Resolve( typeof(IRequestHandler<GenericTestRequest<String>>));
    
    Assert.IsInstanceOf <IRequestHandler<GenericTestRequest<String>>>( requestHandler );
    Assert.IsNotNull( requestHandler );
    }
    }
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Mauricio Scheffer    14 年前

    我认为这里的问题是服务类型是 一个泛型类型定义,而实现类型 . 以下测试全部通过,证明了这一点:

    [Test]
    public void ServiceIsNotGenericTypeDefinition() {
        var service = typeof(IRequestHandler<>).MakeGenericType(typeof(GenericTestRequest<>));
        Assert.IsFalse(service.IsGenericTypeDefinition);
    }
    
    [Test]
    public void ImplementationIsGenericTypeDefinition() {
        var implementation = typeof (GenericTestRequestHandler<>);
        Assert.IsTrue(implementation.IsGenericTypeDefinition);
    }
    
    [Test]
    [ExpectedException(typeof(InvalidOperationException))]
    public void FillOpenGenericType() {
        var service = typeof(IRequestHandler<>).MakeGenericType(typeof(GenericTestRequest<>));
        service.MakeGenericType(typeof (string));
    }
    

    这是因为接口上的实际打开参数类型是“内部”类型,而不是“结果”类型。

    所以这就像在接口中注册一个组件 ICollection (不是一般的 集合 !)和实现类型 List<> . 当你向温莎要 集合 ,它不知道要应用于实现类型的类型参数。

    你的情况更糟,因为你要求 IRequestHandler<GenericTestRequest<String>> 这不是真正注册的。( IRequestHandler<GenericTestRequest<>> )

    希望这是清楚的…