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

Joshua Flanagan
  • 8,527
  • 2
  • 31
  • 40
codecompleting
  • 9,251
  • 13
  • 61
  • 102

2 Answers2

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.

Joshua Flanagan
  • 8,527
  • 2
  • 31
  • 40
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(....);
        }
Suhas
  • 7,919
  • 5
  • 34
  • 54
Glenit
  • 116
  • 4
  • 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(); alright if not tightly coupling two elements? – Glenit Sep 15 '11 at 18:08