leojh
leojh

Reputation: 7712

What is the equivalent of ObjectFactory.Inject in StructureMap 3.0

I recently upgraded to StructureMap 3.0 and noticed that ObjectFactory.Inject is missing. What is the equivalent for simple injection config that this method provided?

Upvotes: 5

Views: 1857

Answers (1)

user1938667
user1938667

Reputation:

As mentioned, 3.0 moved a lot of methods to ObjectFactory.Container. Inject is there, but ObjectFactory will be dropped out at 4.0. So avoid this approach.

Inject and a lot of methods are in the Container class. This is not a static class as ObjectFactory is. To deal with this you can configure like this:

var container = new Container(x =>
{
    x.For<IFooBar>().Use<FooBar>();
}

container.Inject(myObject);

OK, this works only if I'm in the same class, but sometimes you need IContaner class inside a controller and you create your Container at project Startup, in this case you can do this:

public MyController(ISession session, IContainer container)
{
    _session = session;
    _container = container;
}

public void DoSomeStuff()
{
    _container.Inject(new FooBar());
}

IContainer can be injected using your Dependency Resolver. In my case I'm using System.Web.Mvc.DependencyResolver with a custom StructureMapDependencyResolver so this DependencyResolver.Current.GetService<IContainer>().Inject(myService); is possible too.

Upvotes: 6

Related Questions