注入具有多个相同类型参数的构造函数

Ron*_*nin 4 c# autofac

我使用autofac作为DI容器。我的目标是将参数store注入构造函数。那就是我的构造函数的样子。

public SomeClass (IMyCouchStore store)
{
    this.store = store;
} 
Run Code Online (Sandbox Code Playgroud)

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

// sample instantiation
var store = new MyCouchStore("http://someUri","someDbName");
Run Code Online (Sandbox Code Playgroud)

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

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

但是,我收到以下错误:

Autofac.Core.DependencyResolutionException

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

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

Ayd*_*din 7

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

使用UsingConstructor()配置方法显式选择构造函数。


public MyCouchStore(string httpSomeuri, string somedbname)
{
    this.SomeUri = httpSomeuri;
    this.SomeDbName = somedbname;
}
Run Code Online (Sandbox Code Playgroud)
builder.RegisterType<MyCouchStore>()
    .As<IMyCouchStore>()
    .UsingConstructor(typeof (string), typeof (string))
    .WithParameters(new[] 
    {
        new NamedParameter("httpSomeuri", "http://someUri"),
        new NamedParameter("somedbname",  Guid.NewGuid().ToString())
    });
Run Code Online (Sandbox Code Playgroud)