2

Ninject transient scope applies only once, at the moment a class is constructed:

class InjectedClass
{
  [Inject]
  public IClass Instance { get;set;}
}

any call to Instance property from an InjectedClass method will refer to same instance of IClass. Is it possible to return a new instance every time? I don't have a reference to IKernel.

Ivan G.
  • 5,027
  • 2
  • 37
  • 65

2 Answers2

2

In this situation, you want the Factory pattern. Instead of injecting an instance of a type, you inject a factory object and then invoke that method. To use a simple example:

 [Inject]
 public ISomeFactory SomeFactory { get; set; }

 public IClass Instance
 {
     get { return SomeFactory.CreateNew(); }
 }
Tejs
  • 40,736
  • 10
  • 68
  • 86
  • how will the factory create an instance of IClass, should it reference IKernel? – Ivan G. Apr 28 '11 at 15:43
  • Please dont replicate the 'magic property that returns a new instance each time' issue - can you please change Instance to a method please? (And I think you should convert it to Constructor Injection too but thats less critical) – Ruben Bartelink Apr 29 '11 at 08:06
  • Correct - I was just giving a simple example. The factory pattern is more important. – Tejs Apr 29 '11 at 14:26
2

Load the module from: Does Ninject support Func (auto generated factory)?

Then pass a factory function to the constructor:

 public ctor(Func<IClass> classFactory)
 {
     this.classFactory = classFactory;
 }

And create an instance where required this way:

 this.classFactory();

NOTE: I think it is not a good design to pass a new instance to others using a property as in your question. If a class that has this one as dependency you should rather use the mechanism from above inside this other class or if only a single instance is required then use constructor injection instead.

Community
  • 1
  • 1
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98