问题
I am struggling with using the factory extensions for Ninject.
When using the extension in combination with InCallScope, I expected the same instance to be returned from the factory's create method, but instead I get two different instances.
Have I misunderstood the InCallScope concept or do I need to add something else?
using System;
using Ninject;
using Ninject.Extensions.Factory;
using Ninject.Extensions.NamedScope;
namespace MyTest
{
class Program
{
static void Main()
{
var kernel = new StandardKernel();
kernel.Bind<IMyFactory>().ToFactory();
// Does not give what I want, not a surprise...
// kernel.Bind<IMyStuff>().To<MyStuff1>().InTransientScope();
// Works - of course, but I don't want a singleton. It should only be used in call scope...
// kernel.Bind<IMyStuff>().To<MyStuff1>().InSingletonScope();
kernel.Bind<IMyStuff>().To<MyStuff>().InCallScope();
var myFactory = kernel.Get<IMyFactory>();
// Creating my first instance...
var myStuff1 = myFactory.Create();
// Creating my second instance...
var myStuff2 = myFactory.Create();
//
if (myStuff1.SeqNo != myStuff2.SeqNo)
throw new Exception("Except them to be equal...");
}
}
public interface IMyFactory
{
IMyStuff Create();
}
public interface IMyStuff
{
int SeqNo { get; }
}
public class MyStuff : IMyStuff
{
private static int _staticSeqNo;
public MyStuff()
{
SeqNo = _staticSeqNo;
_staticSeqNo++;
}
public int SeqNo { get; private set; }
}
}
回答1:
Ninject.Extensions.ContextPreservation
is the missing link for your case - when its Module is installed in a Kernel, it will change the behavior to what you expect.
But wait... They are separate calls - stuff gets very confusing if they are not (no citations, but discussed with @Remo Gloor informally). For this reason, the Unstable NuGet packages (as of this writing) change the behavior to work as you have.
This question and my two answers should illustrate the problem and hopefully move you towards a solution. Looking for a Ninject scope that behaves like InRequestScope
Your mission, should you choose to accept it is to spread this info into the wiki article that confused you (and me) into expecting the other behavior.
来源:https://stackoverflow.com/questions/16769209/ninject-factory-extension-and-incallscope-does-not-give-expected-results