c# - Dynamically determine Structuremap dependency -


i have service interface, iservice, has multiple implementations retrieves data different data sources. in webapi controller, want dependency resolved during runtime, based on boolean flag set in baseapicontroller custom action filter:

public class baseapicontroller : apicontroller {     // set during runtime custom action filter     public bool condition { get; set; } }  public class mycontroller : baseapicontroller {     private readonly iservice _service;      public mycontroller(iservice service)     {         _service = service;     } 

i want able configure structuremap container such checks condition in base controller, , creates concrete implementation of iservice accordingly.

i'm looking kind of lambda can evaluated @ runtime. i've tried conditionaluse(), doesn't feel correct approach, since seems invoked when building container , not @ runtime.

you use use overload allows specify factory-method. e.g. in registry:

bool istest = true; for<iserviceprovider>().use(      ctx => istest ? (iserviceprovider)ctx.getinstance<foo>() :                      ctx.getinstance<bar>()) 

if have multiple implementations, consider having 2 different registries , use includeregistry determine 1 use @ runtime.


Comments