繁体   English   中英

解决服务时,如何为Unity指定要使用的构造函数?

[英]How can I specify a constructor for Unity to use when resolving a service?

我有以下构造函数:

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注释所需的构造函数:

当一个目标类包含多个具有相同数量参数的构造函数时,必须将InjectionConstructor属性应用于该构造函数

样品:

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

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

尝试InjectionConstructor

container.RegisterType<IReferenceService, ReferenceService>();

更改为

container.RegisterType<IReferenceService, ReferenceService>(new InjectionConstructor());

如果要使用不带参数的那一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM