gpt4 book ai didi

c# - 如何指定 Unity 在解析服务时使用的构造函数?

转载 作者:行者123 更新时间:2023-12-02 19:35:41 25 4
gpt4 key购买 nike

我有以下构造函数:

public ReferenceService(
IAzureTable<Reference> referenceRepository)
{
_referenceRepository = referenceRepository;
}

public ReferenceService(CloudStorageAccount devStorageAccount)
{
_referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}

和 Bootstrapper.cs 中

CloudStorageAccount storageAccount;
storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var container = new UnityContainer();
container.RegisterType<IReferenceService, ReferenceService>();

当我尝试让 Unity 解析我的服务时,它给我一条错误消息,指出有多个带有一个参数的构造函数:

[ResolutionFailedException: Resolution of the dependency failed, type = "WebUx.xController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type ReferenceService has multiple constructors of length 1. Unable to disambiguate.
-----------------------------------------------
At the time of the exception, the container was:

Resolving WebUx.xController,(none)
Resolving parameter "referenceService" of constructor WebUx.xController(
Storage.Services.IContentService contentService,
Storage.Services.IReferenceService referenceService
)
Resolving Storage.Services.ReferenceService,(none) (mapped from Storage.Services.IReferenceService, (none))
]

有没有办法强制 Unity 使用我的两个构造函数之一?

最佳答案

一种方法是使用 InjectionConstructorAttribute 注释您想要的构造函数。 :

When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor

示例:

[InjectionConstructor]
public ReferenceService(IAzureTable<Reference> referenceRepository)
{
_referenceRepository = referenceRepository;
}

public ReferenceService(CloudStorageAccount devStorageAccount)
{
_referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}

关于c# - 如何指定 Unity 在解析服务时使用的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com