Monday, 15 February 2010

c# - How to register and resolve multiple components based on same service -


I have a cached repository that implements the same interface as the real repository. Ie

  public class CachedLocationRepository: ILocationRepository public square LocationRepository: ILocationRepository  

I how both registered do with Autofac and a certain Tell which service to use?

That is, some components are used in real use, using some cached versions

  public class UseRealImpl:. IUseRealImpl {public UseRealImpl (ILocationRepository locationRepository) {}} public class UseCachedImpl: IUseCachedImpl {public UseCachedImpl (ILocationRepository cachedLocationRepository) {}}  

you can use the critters serve to:

for example:

  Kantenrbilder builder = new Kantenrbilder (); Builder.RegisterType & lt; CachedLocationRepository & gt; () As & lt; ILocationRepository & gt; () .Keyed & LT; ILocationRepository & gt; (RepositoryType.Cached); Builder. Registration Type & lt; Location repository & gt; (). Like & lt; ILocationRepository & gt; () .kid & lt; ILocationRepository & gt; (Repository type, real);  

Then can register UseCachedImpl using a parameter:

  builder.RegisterType & LT; UseCachedImpl & gt; () As & lt; UseCachedImpl & gt; () .WithParameter ((pi, c) = & gt; pi.ParameterType == typeof (ILocationRepository), (pi, c) = & gt; c.ResolveKeyed & LT; ILocationRepository & gt; (RepositoryType.Cached));  

or WithKeyAttribute

  public class UseCachedImpl {public UseCachedImpl ([WithKey (RepositoryType.Cached)] ILocationRepository cachedLocationRepository) {} }  

or a module which will automatically add the parameter to the condition of a situation, for example if the service applies some interfaces.


No comments:

Post a Comment