c# - DependencyInjection with a Cache and a Repository that both implement the same interface -


so i've encountered minor conundrum while using dependency injection today (using unity) - have both repository , cache backed repository.

here basic demonstration:

public interface istuffrepo {   stuff getstuff(); }  public class repo : istuffrepo {   public stuff getstuff() {     return get_stuff_from_the_database();  // or   } }  public class stuffcache : istuffrepo {   private stuff _cached;         private istuffrepo _actualrepo;        public stuffcache([dependency] istuffrepo actualrepo) { _actualrepo = actualrepo; }   public stuff getstuff() {     if (_cached != null) return cached_stuff;     _cached = _actualrepo.getstuff(); return _cached;   } } 

i hoping consumer inject istuffrepo, , let di framework , composition root handle building up. i've picked pattern consumer cache , repo identical.

i trying figure how setup composition root build up. way can think of be:

var cache = new stuffcache(container.resolve<stuffrepository>()); container.registerinstance<istuffrepository>(cache); 

but try avoid new-ing , prefer use di framework construction , lifetime management.

is "accepted" way of doing this? there in unity geared towards doing this?

according this msdn doc, if have named mapping particular instance of type, [dependency] annotation can take parameter specify particular mapping use.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -