Zoltán Tamási
Zoltán Tamási

Reputation: 12764

Ninject Factory + InCallScope + ContextPreservation

First of all, I'm aware of the related post here, but that post is quite old, and what's more important, not answered straightly.

So now I use the latest Ninject (stable, 3.2 Nuget packages) and the above mentioned extensions, and still see a non-expected behavior.

public interface IFoo {}
public class Foo {}

public class Parent {
  public IFoo foo;
  public IFoo foo2;
  public Func<IFoo> fooFactory;
  public Parent(IFoo foo, Func<IFoo> factory) {
    this.foo = foo;
    this.fooFactory = factory;
  }
  public void init() { this.foo2 = this.fooFactory(); }
}

...

kernel.Bind<IFoo>().To<Foo>().InCallScope();
var instance = kernel.Get<Parent>();
instance.init();
instance.foo.ShouldEqual(instance.foo2);

This test fails, so it seems like the context is not preserved for the factory function, and it creates a new Foo.

How to achieve the expected behavior?

UPDATE

Based on a comment I've tried the same code with a declared IFooFactory interface bound with ToFactory(). The behavior is the same though.

UPDATE 2

I've just tried with the latest unstable factory and context preservation extensions, and the result is still the same.

Upvotes: 3

Views: 300

Answers (1)

Scott Xu
Scott Xu

Reputation: 11

There are 2 calls. One is kernel.Get<Parent>(), the other is instance.init().

Upvotes: 0

Related Questions