使用Castle Windsor注册/解析部分关闭的泛型子类,使用开放式泛型祖先类型

3

有一个祖先类:

abstract class MyOpenGenericAncestor<T, TOptions>

和子类:

class MyPartiallyClosedDescendant<T> : MyOpenGenericAncestor<T, MyConcreteOptionsType>

我希望能够使用MyOpenGenericAncestor解析MyPartiallyClosedDescendant,例如:
MyOpenGenericAncestor<T, TOptions> ResolveGeneric<T, TOptions>(TOptions options)
{
    // assume options are used for stuff
    return _container.Resolve<MyOpenGenericAncestor<T, TOptions>();
}

有没有一种方法可以实现这个?在当前代码的实现中,注册过程如下:

var assemblyFilter = new AssemblyFilter("C:\\thePath\", "MyStuff.*.dll");
var myTypes = Classes
    .FromAssemblyInDirectory(assemblyFilter)
    .BasedOn(typeof(MyOpenGenericAncestor<,>))
    .WithServiceBase()
    .LifestyleTransient();

container.Register(myTypes);

通过这个注册,MyPartiallyClosedDescendant被注册为一个组件,但是调用ResolveGeneric(myConcreateOptionsInstance)会导致Castle.MicroKernel.ComponentNotFoundException异常,提示没有支持MyOpenGenericAncestor`2[MyConcreateTType, MyConcreateOptionsType]服务的组件被找到。得到这个异常是有道理的,但是是否有一种方法可以通过请求祖先来注册和/或解决后代呢?
1个回答

1
在Castle中,有IGenericImplementationMatchingStrategy用于此目的。不幸的是,我不确定如何将其与约定注册一起使用,所以至少要这样做...
public class MyOpenGenericAncestorMatchingStrategy : IGenericImplementationMatchingStrategy
{
    public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
    {
        return new[] { context.GenericArguments[1] };
    }
}

container.Register(Component.For(typeof(MyOpenGenericAncestor<,>))
.ImplementedBy(typeof(MyPartiallyClosedDescendant<>), new MyOpenGenericAncestorMatchingStrategy()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接