0

I have an interface with multiple classes implementation. I have registered them in Autofac Container. My question how I can resolve for a specific class?

Interface

public interface IAccountDataStorage
{
    Account GetAccount(string accountNumber);
    void UpdateAccount(Account account);
}

Implemented classes

public class BackupAccountDataStore : IAccountDataStorage
{
     ...
}

public class AccountDataStore : IAccountDataStorage
{
     ...
}

Register in container

THIS DOES NOT WORK!

builder.RegisterType<AccountDataStore>().As<IAccountDataStorage>().InstancePerRequest();
builder.RegisterType<BackupAccountDataStore>().As<IAccountDataStorage>().InstancePerRequest();

Now I want to resolve to a specific class

// this does not work for me as it will pick itself one of the 
// above class.. need help here
var paymentService = buildContainer.Resolve<IPaymentService>(); 
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • Does this answer your question? [Resolving Generic Interface with Autofac](https://stackoverflow.com/questions/1189519/resolving-generic-interface-with-autofac) – devNull Nov 15 '20 at 21:51
  • Also, have you read the [Autofac documentation](https://autofaccn.readthedocs.io/en/latest/faq/select-by-context.html) that covers this? – NPras Nov 15 '20 at 21:56
  • No, it did not work for me because I need to verify at decide class at resolve – K.Z Nov 15 '20 at 22:22
  • I have followed this tutorial by register type and resolveTyped and always get the BackupAccountDataStore (2nd one).. https://dotnetfalcon.com/versioning/ – K.Z Nov 15 '20 at 22:39

1 Answers1

0

I have found the answer;

 builder.RegisterType<AccountDataStore>().Keyed("defaultAccountStorage", typeof(IAccountDataStorage));
 builder.RegisterType<BackupAccountDataStore>().Keyed("backupAccountStorage", typeof(IAccountDataStorage));


var a = buildContainer.ResolveKeyed<IAccountDataStorage>("defaultAccountStorage");
var b = buildContainer.ResolveKeyed<IAccountDataStorage>("backupAccountStorage");
K.Z
  • 5,201
  • 25
  • 104
  • 240