注册“半封闭”通用组件

我有两个接口:

public interface IQuery { } public interface IQueryHandler where TQuery : IQuery { TResult Handle(TQuery q); } 

IQueryHandler的封闭实现示例:

 public class EventBookingsHandler : IQueryHandler<EventBookings, IEnumerable> { private readonly DbContext _context; public EventBookingsHandler(DbContext context) { _context = context; } public IEnumerable Handle(EventBookings q) { return _context.Set() .OfEvent(q.EventId) .AsEnumerable() .Select(EventBooking.FromMemberEvent); } } 

我可以使用此组件注册注册并解决IQueryHandler封闭通用实现:

 Classes.FromAssemblyContaining(typeof(IQueryHandler)) .BasedOn(typeof(IQueryHandler)) .WithServiceAllInterfaces() 

但是,我想要做的是解决一个“半封闭”的开放式通用实现(即指定一个通用的TQuery类型参数):

 public class GetById : IQuery where TEntity : class, IIdentity { public int Id { get; private set; } public GetById(int id) { Id = id; } } public class GetByIdHandler : IQueryHandler<GetById, TEntity> where TEntity : class, IIdentity { private readonly DbContext _context; public GetByIdHandler(DbContext context) { _context = context; } public TEntity Handle(GetById q) { return _context.Set().Find(q.Id); } } 

当我尝试解析IQueryHandler<GetById, Event>我遇到了这个exception:

Castle.Windsor.dll中出现“Castle.MicroKernel.Handlers.GenericHandlerTypeMismatchException”类型的exception,但未在用户代码中处理

附加信息:类型Queries.GetById’1 [[Models.Event,Domain,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],Models.Event不满足实现类型Queries.GetByIdHandler’1的generics约束组件’Queries.GetByIdHandler’1’。 这很可能是代码中的错误。

看起来类型已经成功注册,并且我可以告诉约束满足( Event是一个类并实现IIdentity )。 我在这里想念的是什么? 我想做一些温莎无法应付的事情吗?

(我不会将此作为答案发布,就像一些有用的信息一样,评论的信息太多了。)

虽然Castle中的代码失败了:

 public void Resolve_GetByIdHandler_Succeeds() { var container = new Castle.Windsor.WindsorContainer(); container.Register(Component .For(typeof(IQueryHandler<,>)) .ImplementedBy(typeof(GetByIdHandler<>))); var x = container.Resolve, Event>>(); } 

Simple Injector中的相同function:

 public void GetInstance_GetByIdHandler_Succeeds() { var container = new SimpleInjector.Container(); container.RegisterOpenGeneric( typeof(IQueryHandler<,>), typeof(GetByIdHandler<>)); var x = container.GetInstance, Event>>(); }