My code is
public static class ContainerBootstrapper
{
public static void BootstrapStructureMap()
{
ObjectFactory.Initialize(x => x
.ForRequestedType<ValueHolder>()
.CacheBy(InstanceScope.Singleton)
.TheDefaultIsConcreteType<ValueHolder>());
}
}
Initialization code (its a windows service)
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new AppServer()
};
ServiceBase.Run(ServicesToRun);
ContainerBootstrapper.BootstrapStructureMap();
}
}
And then I call an instance like this:
var valueHolder = ObjectFactory.GetInstance<ValueHolder>();
But I get everytime an new instance not the one used before.
I can make some guesses, not familiar enough with StructureMap to make the call. You are very late with calling BootstrapStructureMap() in your main() method. Be sure to call it before you call ServiceBase.Run().
Also, be careful with thread-affinity for the object factory. It is common for code in a service to run on a threadpool thread, a different thread from the one that executes the main() method. If StructureMap stores the singleton in a [ThreadStatic] member, you’ll get a different instance for each thread. Browsing through the StructureMap source code, this is unlikely to be the cause.