在C#Autofac中,如何用多个具体类从单个接口解析类



我有一个具有多个类实现的接口。我已经在Autofac Container中注册了它们。我的问题是,我如何为特定的课程解决?

接口

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

实现类

public class BackupAccountDataStore : IAccountDataStorage
{
...
}
public class AccountDataStore : IAccountDataStorage
{
...
}

在集装箱中注册

这行不通!

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

现在我想解决一个特定的类

// this does not work for me as it will pick itself one of the 
// above class.. need help here
var paymentService = buildContainer.Resolve<IPaymentService>(); 

我找到了答案;

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");

最新更新