gpt4 book ai didi

c# - 注入(inject)具有多个相同类型参数的构造函数

转载 作者:太空狗 更新时间:2023-10-30 00:39:26 25 4
gpt4 key购买 nike

我使用 autofac 作为 DI 容器。我的目标是将参数 store 注入(inject)到构造函数中。这就是我的构造函数的样子。

public SomeClass (IMyCouchStore store)
{
this.store = store;
}

store 参数需要两个字符串参数才能被实例化:

// sample instantiation
var store = new MyCouchStore("http://someUri","someDbName");

我尝试在引导过程中注册这两个参数:

builder
.RegisterType<MyCouchStore>()
.As<IMyCouchStore>()
.WithParameters(new [] {
new NamedParameter("dbUri","http://someUri"),
new NamedParameter("dbName","someDbName")
}

但是,我收到以下错误:

Autofac.Core.DependencyResolutionException

无法在类型“MyCouch.MyCouchStore”上的多个等长 2 的构造函数之间进行选择。在注册组件时,使用 UsingConstructor() 配置方法显式选择构造函数。

如何注入(inject)多个相同类型的参数?

最佳答案

你的答案在你的问题中:)

Select the constructor explicitly, with the UsingConstructor() configuration method.


public MyCouchStore(string httpSomeuri, string somedbname)
{
this.SomeUri = httpSomeuri;
this.SomeDbName = somedbname;
}

builder.RegisterType<MyCouchStore>()
.As<IMyCouchStore>()
.UsingConstructor(typeof (string), typeof (string))
.WithParameters(new[]
{
new NamedParameter("httpSomeuri", "http://someUri"),
new NamedParameter("somedbname", Guid.NewGuid().ToString())
});

关于c# - 注入(inject)具有多个相同类型参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531684/

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