我正在努力使用 Ninject 的工厂扩展。
将扩展与 InCallScope 结合使用时,我希望从工厂的 create 方法返回相同的实例,但我得到了两个不同的实例。
我误解了 InCallScope 概念还是需要添加其他内容?
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; }
}
}