Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy and/or TinyIoC does not respect AsSingleton()

Tags:

c#

nancy

tinyioc

The Setup: I have a almost out-of-the-box Nancy + TinyIoC setup running a webservice which works fine. It depends on various (AsSingleton) service classes. However these are not injected as Singletons, a new instance is created each time.

I have setup the Nancy bootstrapper as follows:

class MyBootStrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        var cp = new CertificateProvider();
        container.Register(cp).AsSingleton();
    }
}
like image 315
Mikkel Løkke Avatar asked Oct 11 '12 15:10

Mikkel Løkke


2 Answers

In your code, even if you would remove AsSingleton() you would still have a singleton, because you are not registering a type or factory but an instance. There is no way TinyIoC is creating new instances of CertificateProvider with that registration.

The only possible thing I can think of is that the bootstrapper itself is executed multiple times but that is a completely different problem and has nothing to do with your registration.

like image 107
Daniel Hilgarth Avatar answered Oct 20 '22 19:10

Daniel Hilgarth


Are you sure your bootstrapper is being used? It's not public so it may well just be using the built in one where the default convention is multiple instances for non-interface dependencies.

As with Daniel's answer.. you also don't need the AsSingleton if you are making an instance registration, you may as well just do:

container.Register<CertificateProvider>().AsSingleton();

So it's only created as needed.

like image 36
Steven Robbins Avatar answered Oct 20 '22 21:10

Steven Robbins