Hi
I am hoping either Peter or Ruben sees this question as they seem to be the go to guys regarding Ninject. I needed to create a custom provider because I have a class that takes 4 arguments. The two can be injected because they are types but the other two are configuration parameters and are integers. They refer to timeouts in milliseconds.
[SingleInstance]
MyClass
{
ISomething something;
IOther other;
int timeout;
int delay;
[Inject]
MyClass(ISomething something, IOther other, int timeout, int delay)
{
this.something = something;
this.other = other;
this.timeout = timeout;
this.delay = delay;
}
}
I was previously relying on a factory that I had created to get the config settings for timeout and delay and to inject something and other. Now it seems to get this right I would have to create my own custom provider. Which I am okay with.
A couple of points of extra points:
- I know I could use injection on the parameters. But that creates a deceptive API. Objects should be returned in a ready to use state and without those 4 arguments it is not ready to use.
- Same argument applies to method injection.
So, my final questions:
- Does that mean that I am in control of ensuring the single instance again or will Ninject still take care of it via the [SingleInstance] attribute?
- Should I not just switch back to the factory I had? What do I gain from using Ninject in this case?
UPDATE: Code sample as requested
Then my provider I assume would like something like this:
class MyClassProvider : SimpleProvider<MyClass> {
protected override MyClass CreateInstance(IContext context) {
int timeout= ConfigurationManager.AppSettings.Get("timeout");
int delay= ConfiguraionManager.AppSettings.Get("delay");
ISomething something = new SomethingImpl();
IOther other = new OtherImpl();
MyClass newOne = New MyClass(something, other, timeout, delay);
}
}
But because I am now using a provider does that bypass ninject's mechanisms of ensuring only a single instance of the object is created so do I have to fall back on:
class MyClassProvider : SimpleProvider<MyClass> {
protected static readonly MyClass myClassInstance;
private static object locker = new object();
protected override MyClass CreateInstance(IContext context) {
if (myClassInstance == null)
{
lock (locker)
{
int timeout = ConfigurationManager.AppSettings.Get("timeout");
int delay = ConfiguraionManager.AppSettings.Get("delay ");
ISomething something = new SomethingImpl();
IOther other = new OtherImpl();
MyClass newOne = New MyClass(something, other, timeout, delay );
}
return MyClassInstance
}
return myClassInstance
}
}
Is there something that I am missing?