Nancy 使用构造函数参数创建单例

Nancy create singleton with constructor parameters

我正在使用 Nancy 和 TinyIoC 来解决依赖关系。

特别需要一个依赖项是应用程序生命周期单例。

如果我用默认构造函数来做,它会起作用:

container.Register<IFoo, Foo>().AsSingleton();   // WORKS

但是如果我在构造函数上尝试使用一些参数,它不会:

container.Register<IFoo>((c, e) => new Foo("value", c.Resolve<ILogger>())).AsSingleton();
// FAILS with error "Cannot convert current registration of Nancy.TinyIoc.TinyIoCContainer+DelegateFactory to singleton"

没有 .AsSingleton(),它再次工作,但我没有得到一个单例:

container.Register<IFoo>((c, e) => new Foo("value", c.Resolve<ILogger>()));
// Works, but Foo is not singleton

有什么想法吗?我认为错误应该很明显,但我找不到。 我已经用完了我所有的 google-foo.


编辑

代码在这里运行:

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        base.ConfigureApplicationContainer(container);

        // here 
    }
}

你在那里做的是告诉 TinyIOC "every time you want one of these, call my delegate",所以如果你想使用那个方法你必须自己处理单例方面。

除非您特别需要延迟创建,否则这样做更容易:

container.Register<IFoo>(new Foo("value", c.Resolve<ILogger>()));

每当您需要 IFoo 时,它将始终使用该实例。