Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject constructor with multiple same typed parameters

Tags:

c#

autofac

I use autofac as DI container. I'm aiming to inject the parameter store into the constructor. That's what my constructor looks like.

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

The store parameter needs two string parameters in order to be instantiated:

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

I tried to register the two parameters during bootstrapping:

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

However, I receive the following error:

Autofac.Core.DependencyResolutionException

Cannot choose between multiple constructors with equal length 2 on type 'MyCouch.MyCouchStore'. Select the constructor explicitly, with the UsingConstructor() configuration method, when the component is registered.

How can I inject multiple same typed parameters?

like image 822
Ronin Avatar asked Feb 21 '16 02:02

Ronin


1 Answers

Your answer is in your question :)

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())
    });
like image 106
Aydin Avatar answered Nov 17 '22 00:11

Aydin