自定义建设开放的仿制药在StructureMap [英] Custom construction with open generics in StructureMap
问题描述
我知道,对structuremap您可以通过指定下列注册泛型类型:
I know that for structuremap you can register generic types by specifying the following:
StructureMapConfiguration
.For(typeof(IRepository<>))
.Use(typeof(RepositoryImplementation<>));
在 ObjectFactory.GetInstance&LT; IRepository&LT;实体&GT;&GT;()
被称为返回相应的实施RepositoryImplementation&LT <$ C C $>;实体&GT; 。
When ObjectFactory.GetInstance<IRepository<Entity>>()
is called the corresponding implementation is returned RepositoryImplementation<Entity>
.
但是,如果我想要一个版本库的包版本?一个版本也实现 IRepository&LT;实体&GT;
- 可以说, CachedRepository&LT;实体&GT;
,有一个构造函数的实现对 IRepository&LT; TEntity&GT;
构造函数: CachedRepository(IRepository&LT;实体&GT; innerRepository)
But what if I want a wrapped version of the repository? A version that also implements IRepository<Entity>
- lets say CachedRepository<Entity>
that has a constructor that takes an implementation of IRepository<TEntity>
ctor: CachedRepository(IRepository<Entity> innerRepository)
.
我如何structuremap返回 CachedRepository&LT;实体&GT;
为IRepository询问时,与concreate RepositoryImplementation为innerRepository
How do I get structuremap to return CachedRepository<Entity>
when asking for an IRepository with the concreate RepositoryImplementation as innerRepository?
推荐答案
一种方法是创建一个自定义类型的拦截器:
One approach is to create a custom type interceptor:
public class CacheMyRepos : TypeInterceptor
{
private readonly Type _openTargetType;
private readonly Type _openWrapperType;
public CacheMyRepos(Type openTargetType, Type openWrapperType)
{
_openTargetType = openTargetType;
_openWrapperType = openWrapperType;
}
public object Process(object target, IContext context)
{
var closedWith = target.GetType().GetGenericArguments()[0];
var closedWrapperType = _openWrapperType.MakeGenericType(closedWith);
return Activator.CreateInstance(closedWrapperType, target);
}
public bool MatchesType(Type type)
{
return type.ImplementsInterfaceTemplate(_openTargetType);
}
}
然后用它注册:
And then register it with:
var container = new Container(x =>
{
x.For(typeof (IRepository<>)).Use(typeof (RepositoryImplementation<>));
x.RegisterInterceptor(
new CacheMyRepos(typeof(IRepository<>), typeof(CachedRepository<>)));
});
这篇关于自定义建设开放的仿制药在StructureMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!