【问题标题】:In C# Autofac, how to resolve class from single interface with multiple concrete classes在 C# Autofac 中,如何从具有多个具体类的单个接口解析类
【发布时间】:2020-11-15 21:22:48
【问题描述】:

我有一个包含多个类实现的接口。我已经在 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>(); 

【问题讨论】:

标签: c# dependency-injection autofac .net-4.8


【解决方案1】:

我找到了答案;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2015-01-09
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2019-10-02
    • 2011-08-25
    相关资源
    最近更新 更多