简体   繁体   中英

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.

Also, when should I call ContainerBuilder.Build() ?

After I call the ContainerBuilder.Build() is it possible to register another type or instance?

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.

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 . 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.

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.

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. I then use a mix of Modules (placed on each assembly that require registration), a assembly "scanner" and MVC integration .

For later registration you could use, for instance, the MEF integration , or, as Jonathan stated, use the Build overload.

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM