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!!
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)));
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<>));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With