Swap out repositories with a flag

断了今生、忘了曾经 提交于 2019-12-24 03:18:35

问题


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?


回答1:


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):

var builder = new ContainerBuilder();

bool cache = GetCacheConfigSetting(); //Up to you where this setting is.    

builder.Register(c => cache ? (IRepository<string>)new CachingRepository<string>(new RealRepos<string>(), new CacheImpl()) : new RealRepos<string>());

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 every Resolve (assuming InstancePerDependency).

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.



来源:https://stackoverflow.com/questions/6226194/swap-out-repositories-with-a-flag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!