I have an Autofac module which has the following (trimmed down) logic in the Load override:
protected override void Load(ContainerBuilder builder)
{
foreach (var componentType in allTypesInAllAvailableAssemblies) // Set elsewhere
{
var handlerInterfaces = componentType.GetInterfaces().Where(i => i.IsClosedTypeOf(typeof(IMessageHandler<>)));
if (handlerInterfaces.Any())
builder.RegisterType(componentType).As(handlerInterfaces);
}
}
This is looking for any class that declares itself a message handler and registers it against all the IMessageHandler interfaces it implements.
What I want to do is not register the component if it's already registered. As a bonus, it would be ideal if I could update the existing registration to resolve against the message handler interface(s) if it isn't already.
For the sake of argument it can be assumed that this code will run after all other types have been registered (including possible message handler candidates)
I've used the AttachToComponentRegistration
override for registration manipulation in the past but it doesn't look like it's useful in this scenario.
Is this possible or should I rethink my design and force plugins to explicitly declare their handlers?
builder.RegisterType(componentType)
.As(handlerInterfaces)
.PreserveExistingDefaults();
Will work.