Nancy and/or TinyIoC does not respect AsSingleton()

1.9k views Asked by At

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();
    }
}
2

There are 2 answers

0
Steven Robbins On BEST ANSWER

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.

1
Daniel Hilgarth On

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.