4

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 
    }
}
Yagnik Detroja
  • 921
  • 1
  • 7
  • 22
Vetras
  • 1,609
  • 22
  • 40

1 Answers1

7

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.

Steven Robbins
  • 26,441
  • 7
  • 76
  • 90