StructureMap configured using container or objectfactory?

I made my configuration as follows:

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 somehow customize the container using Container or ObjectFactory? It was not resolving, so I tested things in a C # console application, and it worked if I did:

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

But this only works if the container is in the local area, and obviously not the case in the web application, since things are connected in global.asax.cs

+6
source share
2 answers

ObjectFactory is a static gateway for a container instance. If you need only one instance of the container and want a simple static way, use ObjectFactory. You must initialize the ObjectFactory and then retrieve the instances via the ObjectFactory.

Alternatively, if you want to control the lifetime of the container yourself, you can instantiate the container by passing the initialization expression to the constructor. Then you retrieve instances from the variable you specify to hold the Container.

In your example, you are mixing two approaches that do not work.

+3
source

I have my setup as shown below

global.asax

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

Then everywhere.

  ObjectFactory.GetInstance<ISomething>(); 

This may not be the only way. Also I think you can find

 Scan(scanner => { scanner.AssemblyContainingType(....); scanner.AddAllTypesOf(....); } 
0
source

Source: https://habr.com/ru/post/897404/


All Articles