StructureMap 3.0中ObjectFactory.Inject的等价物是什么

leo*_*ojh 5 .net c# structuremap dependency-injection structuremap3

我最近升级到StructureMap 3.0并注意到缺少ObjectFactory.Inject.这种方法提供的简单注入配置的等价物是什么?

Ale*_*nzi 6

如上所述,3.0移动了很多方法ObjectFactory.Container.Inject在那里,但ObjectFactory将在4.0退出.所以避免这种方法.

InjectContainer课堂上有很多方法.这不是一个静态类ObjectFactory.要解决这个问题,你可以像这样配置:

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

container.Inject(myObject);
Run Code Online (Sandbox Code Playgroud)

好吧,这只有在我在同一个班级时才有效,但有时你需要IContaner在控制器内部创建你Container的项目Startup,在这种情况下你可以这样做:

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

public void DoSomeStuff()
{
    _container.Inject(new FooBar());
}
Run Code Online (Sandbox Code Playgroud)

IContainer可以使用您的依赖关系解析器注入.在我的情况下,我正在使用System.Web.Mvc.DependencyResolver自定义,StructureMapDependencyResolver所以这DependencyResolver.Current.GetService<IContainer>().Inject(myService);也是可能的.