StructureMap, configure using container or objectfactory?
Asked Answered
M

2

6

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

Madelaine answered 15/9, 2011 at 16:37 Comment(0)
A
3

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.

Approach answered 20/9, 2011 at 1:19 Comment(0)
D
0

I have got mine configured as below

global.asax

  ObjectFactory.Initialize(action =>
            {
                action.For<ISomething>().Use<Something>;
            });

Then everywhere else.

 ObjectFactory.GetInstance<ISomething>();

This may not be the only way though. Also I think what you might be looking for is the

Scan(scanner =>
        {
            scanner.AssemblyContainingType(....);
            scanner.AddAllTypesOf(....);
        }
Dundalk answered 15/9, 2011 at 17:51 Comment(1)
Hi im pretty new to structure map myself - I thought it was only an anti pattern if you were to use ObjectFactory.GetInstance say in an parameterless constructor rather than pass it in through parameters and let the IoC container do the work? Could you elabourate a bit more as I dont wanna pick up bad habbits. are simple calls like IService service = ObjectFactory.GetInstance<IService>(); alright if not tightly coupling two elements?Dundalk

© 2022 - 2024 — McMap. All rights reserved.