用标志交换存储库
我有一个 IRepository< T>与许多 T 和多种实现(按需数据库、Web 服务等)接口。我使用 AutoFac 为许多 T 注册 IRepository,具体取决于我想要为每个 T 提供的存储库类型。
我还有一个基于 .NET 缓存的实现,它在缓存中查找 T,然后调用“真正的”IRepository.Find 来解析缓存未命中。它的构造是这样的:
new CachingRepository(realRepository, cacheImplementation);
我想使用一个配置标志来决定 AutoFac 是否提供基于缓存的 IRepository 或“真实的东西”。看起来“realRepository”来自要求 AutoFac 解析 IRepository << T>但是当客户要求解析相同的接口时,他们会得到什么呢?如果设置了标志,我希望他们获得 CachingRepository。
我不知道如何实施这个基于标志的决议。有什么想法吗?
I have an IRepository< T > interface with many T's and several implementations (on-demand DB, web service, etc.). I use AutoFac to register IRepository's for many T's depending on the kind of repository I want for each T.
I also have a .NET-caching-based implementation that looks for T's in cache and then calls a 'real' IRepository.Find to resolve a cache miss. It is constructed something like this:
new CachingRepository(realRepository, cacheImplementation);
I would like to use a configuration flag to decide if AutoFac serves up caching-based IRepository's or the 'real things.' It seems like 'realRepository' comes from asking AutoFac to resolve IRepository < T > but then what do clients get when they ask to resolve the same interface? I want them to get the CachingRepository if the flag is set.
I can't get my head around how to implement this flag-based resolution. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的选项:条件注册委托
有多种方法可以实现此目的。在注册委托中使用缓存设置可能是最简单的(并说明了委托注册的强大功能):
上面的代码只会读取缓存配置一次。您还可以在注册委托中包含
GetCacheConfigSetting()
。这将导致在每个Resolve
上检查设置(假设InstancePerDependency
)。其他选项:Autofac 装饰器和模块
Autofac 还有一些更高级的功能,您可能也会觉得有用。您问题中的缓存类是装饰器模式的示例。 Autofac 对装饰器有明确的支持。它还有一个很好的模型,用于构建注册和管理配置信息,称为模块 。
Simplest Option: Conditional Registration Delegate
There are a number of ways to do this. Using your cache setting in a registration delegate is probably the simplest (and illustrates the power of delegate registrations):
The code above will only read the cache config once. You could also include the
GetCacheConfigSetting()
in the registration delegate. This would result in the setting being checked on everyResolve
(assumingInstancePerDependency
).Other Options: Autofac Decorators and Modules
There are some more advanced features of Autofac that you may also find useful. The cache class in your question is an example of the Decorator Pattern. Autofac has explicit support for decorators. It also has a nice model for structuring your registrations and managing configuration information, called Modules.