Boris Callens
Boris Callens

Reputation: 93397

Why is this instance initiated by Unity not a singleton?

in my asp.net-mvc application I have a statis MvcApplication that calls a static CreateContainer() method.

In this method I create my unity ioc container:

private static IUnityContainer CreateContainer()
{
    var container = new UnityContainer();
    container.RegisterType<IConfigurationService, ConfigFile>();
    container.RegisterType<ILoggerService, NlogLoggerService>();

    container.RegisterInstance<ISearchService>(
        new LuceneSearchService(
            container.Resolve<IConfigurationService>(),
            container.Resolve<ILoggerService>()),
            new ContainerControlledLifetimeManager());
}

If I understood my sources well, this should give me a singleton LuceneSearchService instance. In my logging however, I can see that my constructor gets hit everytime this instance is requested.

What am I doing wrong?

Upvotes: 1

Views: 4149

Answers (2)

FallenAvatar
FallenAvatar

Reputation: 4079

For a singleton you should move the definition of container outside of the function, and make it static. Set it to null by default.

Then in your CreateContainer function, check if container is null. If it is, create it and initialize it. otherwise, just return it.

private static IUnityContainer container = null;
private static IUnityContainer CreateContainer()
{
    if( container == null )
    {
        container = new UnityContainer();
        container.RegisterType<IConfigurationService, ConfigFile>();
        container.RegisterType<ILoggerService, NlogLoggerService>();

        container.RegisterInstance<ISearchService>(
            new LuceneSearchService(
                container.Resolve<IConfigurationService>(),
                container.Resolve<ILoggerService>()),
                new ContainerControlledLifetimeManager());
    }

    return container;
}

Upvotes: 6

Lee
Lee

Reputation: 144206

I would think that would work, assuming you're resolving an ISearchService and not a LuceneSearchService directly - in that case I think Unity will create a new instance each time as there will be no existing mapping.

Personally, I'd also register it as: container.RegisterType<ISearchService, LuceneSearchService>(new ContainerControlledLifetimeManager());

Upvotes: 1

Related Questions