autofacregistrationautofac-module

Autofac - Add registration after a registration has been added


I want to subscribe an global event which is invoked after a registration has been added.

I don't want to manually subscribe to an event for every registered service/component, because that's boilerplate code and it's easy to forget it when adding new registrations.

When the event fires I want do some checks on the already registered registrations and if a condition is met, e.q it's a named registration and it's a reference type then I want to add additional/new registrations, this should happen before the container is built.

What's the right way to achieve this?

Can I do it in a CustomModule that derives from Module?

Br


Solution

  • Autofac doesn't support "registration events" or anything like that - only resolution events. What you might be able to do is:

    I think some combination of those things should get you what you're looking for. But, unfortunately, there's no event. The reason is that registrations aren't just a simple collection of objects the way they are in Microsoft.Extensions.DependencyInjection - registrations are all callback methods that don't actually execute until you call Build. The final set of registrations is only really available then; and when Build is called, you can't modify that list of callbacks post-facto to add or change registrations.

    That architecture is not likely to change because it's pretty baked into the core of the builder syntax for registrations. The above options are about it.