Injecting a Factory that accepts a Parameter with AutoFac -


i've read on several examples more complex needed , i'm having trouble distilling down simple, concise pattern.

let's have interface names icustomservice , multiple implementations of icustomservice. have class consumer needs determine @ run time icustomservice use based upon parameter.

so create classes follows:

public class consumer {     private customservicefactory customservicefactory;      public consumer(customservicefactory _customservicefactory)     {         customservicefactory = _customservicefactory;     }      public void execute(string parameter)     {         icustomservice service = customservicefactory.getservice(parameter);         service.dosomething();     } }  public class customservicefactory {     private icomponentcontext context;     public customservicefactory(icomponentcontext _context)     {         context = _context;     }      public icustomservice getservice(string p)     {         return context.resolve<icustomservice>(p);  // not correct      } }  public class servicea : icustomservice {     public void dosomething()     {      } }  public class serviceb : icustomservice {     public void dosomething()     {      } } 

is there advantage having factory implement interface? how fix factory , register these classes autofac consumer.execute("a") calls dosomething on workera , consumer.execute("b") calls dosomething on workerb?

thank you

you register implementations of icustomservice keys. example:

builder.registertype<fooservice>.keyed<icustomservice>("somekey"); builder.registertype<barservice>.keyed<icustomservice>("anotherkey"); 

and factory method be:

public icustomservice getservice(string p) {     return context.resolvekeyed<icustomservice>(p); } 

but, can take step further , decouple customservicefactory icomponentcontext:

public class customservicefactory {     private func<string, icustomservice> _create;      public customservicefactory(func<string, icustomservice> create)     {         _create = create;     }      public icustomservice getservice(string p)     {         return _create(p);     } } 

which register so:

builder.register(c => {     var ctx = c.resolve<icomponentcontext>();     return new customservicefactory(key => ctx.resolvekeyed<icustomservice>(key)); }); 

and @ point, assuming customservicefactory doesn't have other behavior omitted question, might use , register func<string, icustomservice> directly.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -