views:

192

answers:

1

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.

+1  A: 

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.

Hans Passant
Yes you were right! It was called to late! After putting it before the Run() call I got finally a singleton instance!And what do you mean with 'be careful with thread-affinity for the object factory' ? I'm comming from webforms so I'm not so familiar with this kind of stuff.
Ignore that, initialization order was clearly your problem.
Hans Passant