So I have a marker interface called `IMessage`.Then I have classes like:

```
public class MessageA: IMessage 
{
}

```

Then I have message handlers defined as:

```
internal interface IMessageHandler<in T> where T: IMessage
{
    void Handle(T message);
}

public class MessageAHandler : IMessageHandler<MessageA> 
{
    public void Handle(T message)
    { 
        //Some logic here
    }
}

```

I want to re-route these messages that I get to the corresponding message handlers when I get a new message. Example:

```
public class MessageReceiver
{
    public void ReceiveMessage(IMessage message)
    {
        //somehow resolve the appropiate message handler here

        messageHandler.Handle(message);
    }
}

```

I can accomplish this right now by using factories like below but I need to have a dependency on each a new factory per different type of message. So I'm wondering if there is a way to create a single factory that will be smart enough to resolve the appropiate message handler?

```
public class MessageReceiver
{
   private readonly Func<IMessageHandler<MessageA>> _messageAFactory;

   public MessageReceiver(Func<IMessageHandler<MessageA>> messageAFactory)
   {
       _messageAFactory= messageAFactory;
   }

   public void ReceiveMessage(IMessage message)
   {
       if (message is MessageA)
       {
           var messageHandler = _messageAFactory();
           messageHandler.Handle(message as MessageA);
       }

       // Add more if-statements here for more messages
   }
}

```

---

Autofac Registration

```
public class InfrastructureModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        //Register the types in the infrastructure assembly
        builder.RegisterAssemblyTypes(ThisAssembly).AsImplementedInterfaces()
            .InstancePerLifetimeScope();

        //Register the message handlers
        builder.RegisterAssemblyTypes(ThisAssembly)
        .Where(x => x.IsAssignableFrom(typeof(IMessageHandler<IMessage>)))
        .InstancePerDependency().AsImplementedInterfaces();
    }
}

```