Multiple length 2 constructors. Unity cannot be fixed unambiguously
I want to use DI with a repository class and an interface for MongoDB, but it doesn't work. I have this error:
The MongoRepository`1 type has multiple length 2 constructors. Cannot 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 do I set up DI in Unity? Thank!!
+3
source to share
2 answers
The solution is simple: don't use automatic posting when working with frame types as described in this article .
Instead, register a factory delegate for the frame types. This, however, will not work in your case, since you are dealing with a generic type, but working around is simple again: 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<>));
+3
source to share