Question

I would like to use a common Autofac module in several different web projects.

One of these projects does not require all the classes registered in my common module (it uses about half of them). My guess was that if a class is registered but never called, it will not be resolved and so it will not use up extra memory.

Is this ok or bad practice ? Thanks

Was it helpful?

Solution

I think that the amount of extra memory consumed by Autofac (or any DI container) is minimal -if- those types are never resolved. Containers have lazy-load mechanism, which prevents slow startups. When a type is resolved for the first time, containers often generate a lot of code and memory in the background to be able to do fast resolves at any later request for that type. Do note though that containers that contain some sort of 'verify' feature often force an instance to be created which will trigger the whole building and compilation process. So if you call this verify feature during startup, you lose the lazy-loading benefits.

Some developers even go a step further and tel the container to go reflect over all assemblies and register any type it finds by its interfaces. When doing this, you might see a lot of types ending up in the container that are never used and can actually never be resolved (because they weren't intended to be created by the container). The idea is that this keeps the container configuration very simple, and they don't care about the extra garbage.

Although this can simplify the container's configuration, downside of this approach is that this makes it much harder to have a simple integration test that verifies the correctness of the DI configuration, because there will be a lot of false-positives; the test will constantly fail because there are a lot of invalid registrations in the container. And it gets even worse if your container contains some sort of diagnostic service that allows detecting common misconfigurations. Again such configuration will trigger lots of false-positives or might even disable this feature altogether (depending on the framework you use).

That's why I usually advice against doing this type of batch-registration (although I'm not against batch registration itself).

OTHER TIPS

Performance wise probably not, but...

...this means that you also have to add unneeded references to your project. I would avoid it to keep the amount of dependencies as low as possible. According to me, registering dependencies is something that belongs to your application, and not something that is shared across multiple applications. After all, things like life time may vary depending on the application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top