我知道对于结构图,您可以通过指定以下内容来注册泛型类型:
StructureMapConfiguration
.For(typeof(IRepository<>))
.Use(typeof(RepositoryImplementation<>));
当调用 ObjectFactory.GetInstance>()
时,返回相应的实现 RepositoryImplementation< /代码>。
但是如果我想要存储库的包装版本怎么办?还实现了 IRepository
的版本 - 假设 CachedRepository
具有一个采用 IRepository
实现的构造函数构造函数:CachedRepository(IRepositoryinnerRepository)
。
当请求使用 concreate RepositoryImplementation 作为innerRepository 的 IRepository 时,如何让结构图返回 CachedRepository ?
I know that for structuremap you can register generic types by specifying the following:
StructureMapConfiguration
.For(typeof(IRepository<>))
.Use(typeof(RepositoryImplementation<>));
When ObjectFactory.GetInstance<IRepository<Entity>>()
is called the corresponding implementation is returned RepositoryImplementation<Entity>
.
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)
.
How do I get structuremap to return CachedRepository<Entity>
when asking for an IRepository with the concreate RepositoryImplementation as innerRepository?
发布评论
评论(2)
一种方法是创建一个自定义类型拦截器:
然后将其注册为:
One approach is to create a custom type interceptor:
And then register it with:
CachedRepository
是否必须与任何具体实现配合使用,或者将其绑定到RepositoryImplementation
是否安全?如果可以绑定,这应该可以解决问题:然后将 CachedRepository 构造函数更改为 CachedRepository(RepositoryImplementation insideRepository)。
Does
CachedRepository<Entity>
have to work with any concrete implementation, or is it safe to tie it toRepositoryImplementation<Entity>
? If it can be tied, this should do the trick:Then change the CachedRepository constructor to
CachedRepository(RepositoryImplementation<Entity> innerRepository)
.