给构造函数注入多个同类型参数

5

我使用autofac作为DI容器。 我想将参数store注入到构造函数中。 这是我的构造函数的样子。

public SomeClass (IMyCouchStore store)
{
    this.store = store;
} 
< p >“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' 类型上有多个长度相等的构造函数,无法选择。当组件被注册时,请使用 UsingConstructor() 配置方法显式地选择构造函数。
我该如何注入多个相同类型的参数?

1
错误提示:通过 UsingConstructor() 明确选择构造函数。 - Aydin
1个回答

12

你的回答已经在你的问题中了 :)

使用 UsingConstructor() 配置方法明确地选择构造函数。

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())
    });

我查阅了Autofac文档,但未能找到任何与我的用例相符的示例。您能提供一个示例吗? - Ronin
1
那应该解决了 ;) - Aydin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接