使用Fluent界面从头开始在Castle Windsor中注册所有课程 [英] Register all classes from base on up in Castle Windsor using Fluent interface
问题描述
我有一个抽象基类 Search
。抽象类 IndexedRepositorySearch
源自 Search
。 FacetSearch
的抽象类来自 IndexedRepositorySearch
。具体类 IngredientFacetSearch
和 RecipeFacetSearch
属于 FacetSearch
。
I have an abstract base class Search
. An abstract class IndexedRepositorySearch
descends from Search
. An abstract class FacetSearch
descends from IndexedRepositorySearch
. Concrete classes IngredientFacetSearch
and RecipeFacetSearch
descend from FacetSearch
.
当前,我们正在将 Search
产生的所有内容注册到温莎城堡:
Currently we're registering everything that descends from Search
with Castle Windsor as follows:
AllTypes.FromAssembly(assembly)
.BasedOn<Search.Search>()
.WithServiceBase()
.WithServiceSelf()
.LifestyleTransient()
.AllowMultipleMatches()
然后我们打电话
_container.ResolveAll<FacetSearch>(new { searchInput = input, searchResults });
它无法解析容器中的任何内容。当所有内容都已注册后在容器上放置一个断点并在调试器中检查 AllComponents
时,我同时看到了 IngredientFacetSearch
和 RecipeFacetSearch
,但是它们每个都只有两个与之关联的服务:它们的自身和基础的 Search
。考虑到他们在 .WithServiceBase()
和 .WithServiceSelf()
中注册的期望。
It does not resolve anything from the container. When I put a breakpoint on the container after everything has been registered and check AllComponents
in the debugger, I see both IngredientFacetSearch
and RecipeFacetSearch
, but they each only have two Services associated with them: their self and Search
, their base. Which you would expect given that they registered with .WithServiceBase()
and .WithServiceSelf()
.
所以问题是如何通过调用 ResolveAll< FacetSearch>()
使他们解决?
So the question is how to get them to resolve by calling ResolveAll<FacetSearch>()
?
我敢肯定这很简单,但是如果我能找到它,我会很惊讶。
I'm sure it's something simple but I'll be darned if I can find it.
请先谢谢。
推荐答案
对此我们有一个类似的问题,但是只需要注册第一个抽象的库即可。我使用 WithServiceSelect
解决了这个问题,但将其包装成扩展方法以供使用:
We had a simliar problem to this, but only needed to register the first base which was abstract. I solved it using WithServiceSelect
but wrapped it up into an extension method to be used so:
AllTypes.FromAssembly(assembly)
.BasedOn<Search.Search>()
.WithServiceLastAbstractBase(),
扩展方法的定义为:
public static BasedOnDescriptor WithServiceLastAbstractBase(this BasedOnDescriptor basedOn)
{
return basedOn.WithServiceSelect(selectLastAbstractBase);
}
private static IEnumerable<Type> selectLastAbstractBase(Type type, Type[] basetypes)
{
var baseType = type;
do
{
baseType = baseType.BaseType;
} while (baseType != null && !baseType.IsAbstract);
if (baseType == null)
{
throw new ArgumentException("There are no abstract base types for: " + type);
}
return new [] { baseType };
}
这篇关于使用Fluent界面从头开始在Castle Windsor中注册所有课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!