Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy create singleton with constructor parameters

I'm using Nancy with TinyIoC to solve the dependencies.

One dependency in particular needs to be application-lifecycle singleton.

If I do it with a default constructor it works:

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

but if i try this with some arguments on the contructor it does not:

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"

Whithout .AsSingleton(), it works again, but I don't get a singleton:

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

Any Ideas? I think the mistake should be obvious but I can't find it. I've used up all my google-foo.


EDIT

The code runs here:

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

        // here 
    }
}
like image 703
Vetras Avatar asked Mar 13 '23 16:03

Vetras


1 Answers

What you're doing there is telling TinyIOC "every time you want one of these, call my delegate", so if you want to use that method you have to handle the singleton aspect yourself.

Unless you particularly need the deferred creation it's easier to do:

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

That will then always use that instance whenever you want an IFoo.

like image 131
Steven Robbins Avatar answered Mar 24 '23 10:03

Steven Robbins