user137348
user137348

Reputation: 10332

StructureMap singleton behavior not working

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.

Upvotes: 1

Views: 1837

Answers (2)

Gregor
Gregor

Reputation: 388

I am having the same problem..i am using a structure map container inside a factory and can also not get the singelton to work.!

For<IServiceD>().Singleton().Use<ServiceD>();

It seems to work only for transiently created objects but not for explicitly created objects. (using Google search "transiently , structure map" you should find something on this. )

The same applies to subcontainers:

private IContainer myParentContainer;
private IContainer myIoc;
...
myIoc = myParentContainer.GetNestedContainer(); 

and pulling instances out of myIoc are then unique, but only so long as they are created transiently..

I just finding it confusing having to differentiate between transiently created objects and other bojects and to code around this. In ten years from now, nobody is going to understand this difference anymore. It needs to be simpler than this.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942109

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.

Upvotes: 1

Related Questions