[英]Is Autofac ContainerBuilder.Build an expensive operation?
I'm starting to use Autofac and I can't seem to find an answer to this question. 我开始使用Autofac,我似乎无法找到这个问题的答案。
Also, when should I call ContainerBuilder.Build() ? 另外,我什么时候应该调用ContainerBuilder.Build()?
After I call the ContainerBuilder.Build() is it possible to register another type or instance? 我调用ContainerBuilder.Build()之后是否可以注册另一个类型或实例?
I can't tell you whether or not the Build method is expensive or not, but if you follow the Register Resolve Release pattern it doesn't matter because you should only have a single container instance per application. 我不能告诉你Build方法是否昂贵,但是如果你遵循Register Resolve Release模式,那就无所谓了,因为每个应用程序只应该有一个容器实例 。
You need to invoke the Build method once to get a container instance, so no matter how expensive (or not) it is, this is a cost you must pay . 您需要调用Build方法一次才能获得容器实例,因此无论它有多贵(或不是), 这都是您必须支付的成本 。 However, when you only use a single instance of the container, you only pay that cost once .
但是,当您只使用容器的单个实例时,您只需支付一次该费用 。
ContainerBuilder.Build() should generally be called during application startup before you actually start invoking business behavior. 在实际开始调用业务行为之前,通常应在应用程序启动期间调用ContainerBuilder.Build()。
If you need to register additional components into an existing container you can. 如果需要将其他组件注册到现有容器中,则可以。 To do this in Autofac v2.2 (or later), you can create another ContainerBuilder instancer and use the ContainerBuilder.Build(IContainer) overload method.
要在Autofac v2.2(或更高版本)中执行此操作,您可以创建另一个ContainerBuilder实例并使用ContainerBuilder.Build(IContainer)重载方法。
ContainerBuilder _AutoFacContainerBuilder;
IContainer _AutoFacContainer;
_AutoFacContainerBuilder.RegisterType<MyClass>().Named<IMyClass>("MyNameOne");
_AutoFacContainer = AutoFacContainerBuilder.Build();
ContainerBuilder _AnotherBuilder;
_AnotherBuilder.RegisterType<MyClassTwo>().Named<IMyClassTwo>("MyNameTwo");
_AnotherBuilder.Update(_AutoFacContainer);
In my web apps I use a base HttpApplication class that calls the Build on the Application_Start event. 在我的Web应用程序中,我使用了一个基本的HttpApplication类,它在Application_Start事件上调用Build。 I then use a mix of Modules (placed on each assembly that require registration), a assembly "scanner" and MVC integration .
然后我使用混合模块 (放置在需要注册的每个组件上), 组件“扫描器”和MVC集成 。
For later registration you could use, for instance, the MEF integration , or, as Jonathan stated, use the Build overload. 对于以后的注册,您可以使用,例如, MEF集成 ,或者,如Jonathan所述,使用Build重载。
Hope it helps :) 希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.