【问题标题】:StructureMap and Generics - How do I specify a default constructor?StructureMap 和泛型 - 如何指定默认构造函数?
【发布时间】:2012-05-15 14:00:03
【问题描述】:

我有一个通用接口:

public interface IRepository<T> { ... }

我有一个这样的实现:

public class Repository<T> {
    public Repository<T>() { ... }
}

StructureMap (v 2.6.3) 配置如下:

For(typeof(IRepository<>)).Use(typeof(Repository<>));

当我尝试从 StructureMap 中提取 IRepository&lt;Something&gt; 时,我得到了预期的 Repository&lt;Something&gt;万岁!

现在我添加了第二个构造函数,实现如下所示:

public class Repository<T> {
    public Repository<T>() { ... }
    public Repository<T>(string database) { ... }
} 

当我现在尝试获取IRepository&lt;Something&gt; 时,我得到一个异常,因为它默认尝试使用带有参数的新构造函数。 嘘!

如何更改我的 StructureMap 配置,使其知道使用无参数构造函数?

【问题讨论】:

    标签: c# generics inversion-of-control structuremap


    【解决方案1】:

    您可以通过使用 [DefaultConstructor] 属性标记您希望 StructureMap 使用的构造函数来实现此目的。正如您在StructureMap documentation 上看到的,默认情况下它是贪婪的。

    【讨论】:

    • 是的,我找到了解决方案...但是,我不想更改我的 Repository 类,除非我真的必须这样做。必须将实现与特定的 IOC 容器紧密耦合似乎很奇怪。
    • 对于开放的泛型类型没有办法做到这一点。作为一个讨厌的 kludge,您可以使用 CtorDependency 例如传递一个默认值。 x.For(typeof(IRepository)).Use(typeof(Repository)).CtorDependency("database").Is(null);然后相应地处理它。数据库字符串是做什么用的?为什么不希望你的容器实现它?
    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多