c# - Ninject. Optional Injection -
i have global flags enable/disable features. i'd inject dependencies depending on flag. features require classes heavily constructed want inject null if value of flag false , actual dependency otherwise. ninject doesn't allow injecting null. there other options?
update: constructor arguments can decorated optionalattribute
attribute. in case null injected if there no corresponding binding found. there problem here: can't verify if target class can constructed. have test each public dependency verifies if can constructed successfully. in case if value of flag true not able find error when dependency decorated optionalattribute
attribute, cannot constructed properly. i'd manage on binding level only.
you can vary injection behaviour binding using factory method (i.e. tomethod
), , it's possible allow injection of nulls configuring container's allownullinjection
setting.
another alternative use factory method , supply lightweight dummy object instead of heavy-weight class. if using interfaces straightforward, have implementations of interface nothing. use mocking framework such fakeiteasy construct these dummies you. benefit here, dummy makes special behaviour transparent clients i.e. clients not need check null
, etc.
an example of using factory method, plus allownullinjection
, nulls:
public void configure() { bool create = true; ikernel kernel = new standardkernel(); kernel.settings.allownullinjection = true; kernel.bind<ifoo>().tomethod(ctx => create ? ctx.kernel.get<foo>() : null); dependendsonifoo depfoo = kernel.get<dependendsonifoo>(); } private interface ifoo {} private class foo : ifoo {} private class dependendsonifoo { public dependendsonifoo(ifoo foo) {} }
and example lightweight object substituted depending on flag:
public void configure() { bool heavy = true; ikernel kernel = new standardkernel(); kernel.bind<ifoo>() .tomethod(ctx => heavy ? ctx.kernel.get<heavyfoo>() : (ifoo)new dummyfoo()); dependendsonifoo depfoo = kernel.get<dependendsonifoo>(); } private interface ifoo {} private class heavyfoo : ifoo {} private class dummyfoo : ifoo { } private class dependendsonifoo { public dependendsonifoo(ifoo foo) {} }
Comments
Post a Comment