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?
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;
}