简体   繁体   English

NancyFx和TinyIoC为模块提供单个实例

[英]NancyFx and TinyIoC provide single instance to module

Iv got a fairly simlpe question. iv有一个相当简单的问题。 Im using Nancy with a windows form (passed through the constructor (autoresolve)). 我在Windows窗体中使用了南希(通过构造函数(autoresolve)传递)。 If i let nancy resolve automatically every module it creates a new instance of the form, which is not what i want. 如果我让nancy自动解析每个模块,它将创建表单的新实例,这不是我想要的。 I thought maybe i could register my form instance in TinyIoC and then it would always use just this instance instead of creating a new one each time. 我以为我可以在TinyIoC中注册我的表单实例,然后它总是只使用该实例,而不是每次都创建一个新实例。 But that has proved not as simple to implement as the idea is. 但是事实证明,实现起来并不像这个想法那么简单。

Thanks in advance 提前致谢

you should probably do this in the bootstrapper 您可能应该在引导程序中执行此操作

something like: 就像是:

public class MyBootstrapper: DefaultNancyBootstrapper
{
    ConfigureApplicationContainer (TinyIoCContainer container)
    {
        //the .AsSingleton() instructs TinyIOC to make only one of those.
        container.Register<IMessageDeliverer>().AsSingleton();
        base.ConfigureApplicationContainer (container);            
    }
}

I resolved this by not assigning the window reference to the contructor but by registering it with TinyIoC and the resolving it in the default constructor 我没有通过将窗口引用分配给构造函数来解决此问题,而是通过在TinyIoC中注册了它并在默认构造函数中进行了解析

//Registering in form
var container = TinyIoCContainer.Current;
container.Register<IMessageDeliverer>(this);

//Resolving in Module Constructor
var container = TinyIoCContainer.Current;
IMessageDeliverer mdl = container.Resolve<IMessageDeliverer>();
setDeliverer(mdl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM