inversion of control - Autofac named registration constructor injection -


does autofac support specifying registration name in components' constructors?

example: ninject's namedattribute.

you need use autofac.extras.attributed package on top achieve this

so let's have 1 interface , 2 classes:

public interface ihello {     string sayhello(); }  public class englishhello : ihello {     public string sayhello()     {         return "hello";     } }  public class frenchhello : ihello {     public string sayhello()     {         return "bonjour";     } } 

then have consumer class, in want select instance injected:

public class helloconsumer {     private readonly ihello helloservice;      public helloconsumer([withkey("en")] ihello helloservice)     {         if (helloservice == null)         {             throw new argumentnullexception("helloservice");         }         this.helloservice = helloservice;     }      public string sayhello()     {         return this.helloservice.sayhello();     } } 

registering , resolving:

containerbuilder cb = new containerbuilder();  cb.registertype<englishhello>().keyed<ihello>("en"); cb.registertype<frenchhello>().keyed<ihello>("fr"); cb.registertype<helloconsumer>().withattributefilter(); var container = cb.build();  var consumer = container.resolve<helloconsumer>(); console.writeline(consumer.sayhello()); 

do not forget attributefilter when register such consumer, otherwise resolve fail.

another way use lambda instead of attribute.

cb.register<helloconsumer>(ctx => new helloconsumer(ctx.resolvekeyed<ihello>("en"))); 

i find second option cleaner since avoid reference autofac assemblies in project (just import attribute), part personal opinion of course.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -