Use factory to resolve dependencies

Viewed 171

We have a websolution with autofac. Now we want to reuse things in a windows service/console app where things are only available when a message comes in from an enterprise bus.

I have the following service to reuse

public SettingsService : ISettingsService {
    public readonly ITenantIdentifer _tenantIdentifier
    public SettingsService (ITenantIdentifier tenantIdentifier) {
       this._tenantIdentifier =tenantIdentifier; 
    }
    // do other stuff
}

The current working setup

the ITenantIdentifier for the webcontext is simply registered for the webapplication using builder.RegisterType<WebTenantIdentifier>().As<ITenantIdentifier>();.
Evething works fine.

Our enterprise bus

The enterprise bus can not resolve the ITenantIdentifier until the message is available. So we created a MessageTenantIdentifier and registered a factory.

 public class MessageTenantIdentifier : ITenantIdentifier
 {
    public delegate MessageTenantIdentifier Factory(int tenantId);
public MessageTenantIdentifier(int tenantId, IOtherDependency stuff)
    {
        _tenantId = tenantId;
        // ...
    }
}

// somewhere else the this is registered     
builder.RegisterType<MessageTenantIdentifier >().As<ITenantIdentifier>().AsSelf();
builder.RegisterGeneratedFactory<MessageTenantIdentifier.Factory>();

The problem The factory can only be used when the message is being handled in a

public class MsgTypeHandler : IHandleMessages<MsgType>
{
    public MsgTypeHandler(ISettingsService settingsService, MessageTenantIdentifier factory) { ...}
    public async Task Handle(MsgType message)
    {
        var tenantId = message.TenantId;
        // THIS IS THE MOMENT I CAN CONFIGURE THE MessageTenantIdentifier
        var tenantIdentifier = factory.Invoke(tenantId);

        // but this factory is not used against the ISettingsService.  The service to be reused.  <== THE REAL PROBLEM
    }
}

The question

So, how can I solve this issue? E.g. how should I setup the registration of the MessageTenantIdentifier in the servicebus? Or is my dependency setup just plain wrong?

1 Answers
Related