使用Castle Windsor中的Generic参数解析Generic

时间:2009-11-04 21:47:10

标签: .net inversion-of-control castle-windsor ioc-container

我正在尝试注册一个类似IRequestHandler 1[GenericTestRequest 1 [T]]的类型,它将由GenericTestRequestHandler`1 [T]实现,但我目前收到来自Windsor的错误“Castle.MicroKernel.ComponentNotFoundException:No支持服务的组件“是否支持这种类型的操作?或者它是否远离支持的寄存器(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 个答案:

答案 0 :(得分:4)

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

[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(不是通用ICollection!)和实现类型List<>的组件。当您向Windsor询问ICollection时,它不知道要应用于实现类型的类型参数。

在你的情况下,情况会更糟,因为你要求的IRequestHandler<GenericTestRequest<String>>并没有真正注册。 (IRequestHandler<GenericTestRequest<>>

希望很清楚...