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] 的组件。获得该异常是有道理的,但是有没有办法通过请求祖先来注册和/或解决后代?

4

1 回答 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()));
于 2017-09-02T11:04:46.353 回答