Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple constructors of length 2. Unable to disambiguate with Unity

I want to use DI with a Repository Class and Interface for MongoDB, but it's not working. I have this error:

The type MongoRepository`1 has multiple constructors of length 2. Unable to disambiguate.

Class Constructors:

    public MongoRepository(string connectionString, string collectionName)
    {
        this.collection = Util<TKey>.GetCollectionFromConnectionString<T>(connectionString, collectionName);
    }


    public MongoRepository(MongoUrl url, string collectionName)
    {
        this.collection = Util<TKey>.GetCollectionFromUrl<T>(url, collectionName);
    }

Unity Config:

container.RegisterType(typeof(MongoRepository.IRepository<>), typeof(MongoRepository.MongoRepository<>));

How can I configure the DI in Unity? Thanks!!

like image 366
chemitaxis Avatar asked Aug 29 '14 09:08

chemitaxis


2 Answers

Note that you can also tell Unity which constructor it should use:

//Use the MongoRepository(string, string) constructor:
container.RegisterType(
    typeof(IRepository<>), 
    typeof(MyMongoRepository<>),
    new InjectionConstructor(typeof(string), typeof(string)));
like image 89
Leon Bouquiet Avatar answered Nov 14 '22 21:11

Leon Bouquiet


The solution is simple: don't use auto-wiring when dealing with framework types, as explained in this article.

Instead register a factory delegate for framework types. This however won't work in your case since you're dealing with a generic type, but the work around again is simple: create a derived type and register that:

public class MyMongoRepository<T> : MongoRepository<T>
{
    // of course you should fill in the real connection string here.
    public MyMongoRepository() : base("connectionString", "name") { }
}

container.RegisterType(typeof(IRepository<>), typeof(MyMongoRepository<>));
like image 34
Steven Avatar answered Nov 14 '22 22:11

Steven