c# - Inject a singleton with parameters -


using ninject, have interface want bind single instance of concrete implementation. example:

public interface ifoo { //... } public class foo { //... } 

now normally, i'd bind like so:

kernel.bind<ifoo>().to<foo>().insingletonscope(); 

but, need add parameters constructor foo. normally, again, wouldn't of problem (i think):

kernel.bind<ifoo>()     .to<foo>()     .insingletonscope()     .withconstructorargument("bar", mybar); 

now problem can't know value of mybar @ time set bindings. need defer until first time need ifoo (and note, in reality have several arguments pass). need singleton, lazy initialized on first use , gets arguments @ point.

what's best way approach this? i'm assuming factory solution, don't quite see right way this. don't want create new foo every time.

as in comment above. real problem may not have construction parameters when need foo. in pattern can bind interfaces please , call iinitialiser.initialise when ready (obvs need keep reference or make static).

foo throw exception if call before been set up

ifoo remains unchanged

iinitialiser implementations can tweaked poll db or respond events or whatever suits late configuration senario best

using system;  namespace unittestproject3 {     public interface ifoo     {         int getallthefoo();     }      public interface iinitialiser     {         void initialise(int x);          int getx();          bool isready { get; }     }      public class foo : ifoo     {         private bool isinitalised;         private int x;         private iinitialiser i;         public foo(iinitialiser i)         {             this.isinitalised = false;             this.i = i;         }          protected void init()         {             if (this.isinitalised)             {                 return;             }             else if (i.isready)             {                 x = i.getx();                 this.isinitalised = true;                 return;             }             else             {                 throw new exception("you have not set x");             }         }          public int getallthefoo()         {             init();             return x;         }     }  } 

Popular posts from this blog