开发者

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.GetIn开发者_开发百科stance<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


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.


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(....);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜