Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap, configure using container or objectfactory?

I did my configuration like this:

var container = new Container(x =>
                                              {
                                                  x.For<IEngine>().Use<V6Engine>();
                                                  x.For<ICar>().Use<HondaCar>();
                                              }
);

Then in my mvc controller action I did:

ICar car = ObjectFactory.GetInstance<ICar>();

Should I be setting up my container using Container or ObjectFactory somehow? It didn't resolve, so I tested things out in a c# console application and it worked if I did:

ICar car = container.GetInstance<ICar>();

But this only works if container is in local scope, and in a web app it isn't obviously since things are wired up in global.asax.cs

like image 817
codecompleting Avatar asked Sep 15 '11 16:09

codecompleting


1 Answers

ObjectFactory is a static gateway for an instance of container. If you only ever want one instance of a container, and want a simple static way to get at it, use ObjectFactory. You must Initialize the ObjectFactory, and then retrieve your instances via ObjectFactory.

Alternatively, if you want to manage the lifetime of the container yourself, you can create an instance of Container, passing an initialization expression to the constructor. You then retrieve instances from the variable you declared to store the Container.

In your example, you are mixing the two approaches, which doesn't work.

like image 178
Joshua Flanagan Avatar answered Nov 03 '22 00:11

Joshua Flanagan