我有以下构造函数:
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使用我的两个构造函数之一?
答案 0 :(得分:4)
一种方法是使用InjectionConstructorAttribute注释所需的构造函数:
当目标类包含多个具有相同参数数量的构造函数时,必须将InjectionConstructor属性应用于构造函数
样品:
[InjectionConstructor]
public ReferenceService(IAzureTable<Reference> referenceRepository)
{
_referenceRepository = referenceRepository;
}
public ReferenceService(CloudStorageAccount devStorageAccount)
{
_referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}
答案 1 :(得分:2)
container.RegisterType<IReferenceService, ReferenceService>();
更改为
container.RegisterType<IReferenceService, ReferenceService>(new InjectionConstructor());
如果你想使用没有参数的那个。