【问题标题】:Multiple constructors of length 2. Unable to disambiguate with Unity长度为 2 的多个构造函数。无法与 Unity 消除歧义
【发布时间】:2014-08-29 09:14:56
【问题描述】:

我想将 DI 与 MongoDB 的存储库类和接口一起使用,但它不起作用。我有这个错误:

MongoRepository`1 类型有多个长度为 2 的构造函数。无法消除歧义。

类构造函数:

    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);
    }

统一配置:

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

如何在 Unity 中配置 DI?谢谢!!

【问题讨论】:

  • 老实说,人们会为此大发雷霆,真正的解决方案是停止使用 Unity 并使用像 Autofac 这样的体面的 IoC 容器来处理任何你想扔给它的东西。 Unity 几乎在每一个障碍中都失败了。

标签: c# mongodb dependency-injection unity-container


【解决方案1】:

请注意,您还可以告诉 Unity 它应该使用哪个构造函数:

//Use the MongoRepository(string, string) constructor:
container.RegisterType(
    typeof(IRepository<>), 
    typeof(MyMongoRepository<>),
    new InjectionConstructor(typeof(string), typeof(string)));

【讨论】:

  • 这个解决方案对我有用,比接受的答案更简单
【解决方案2】:

解决方案很简单:在处理框架类型时不要使用自动装配,如this article 中所述。

改为为框架类型注册一个工厂委托。但是,这在您的情况下不起作用,因为您正在处理泛型类型,但解决方法很简单:创建一个派生类型并注册它:

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<>));

【讨论】:

  • 为什么它能解决我的问题? container.RegisterType, MongoRepository.MongoRepository> (new InjectionConstructor());
  • @chemitaxis:它解决了你的问题,因为现在你有了一个带有 Unity 知道如何调用的构造函数的泛型类型。你试过了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多