7

我正在尝试使用结构图在我的项目中配置 NCommon NHRepository。如何阻止它选择最贪婪的构造函数?

 public class NHRepository<TEntity> : RepositoryBase<TEntity>
 {

    public NHRepository () {}


    public NHRepository(ISession session)
    {
        _privateSession = session; 
    }

    ...
}

我的结构图配置

ForRequestedType(typeof (IRepository<>))
                .TheDefaultIsConcreteType(typeof(NHRepository<>))

干杯杰克

4

2 回答 2

8

您可以将[DefaultConstructor]您希望的构造函数的属性设置为默认值。在您的情况下,在NHRepository()构造函数上设置它会使其成为 StructureMap 初始化的默认构造函数。

更新:好吧,在最新版本的 StructureMap 中,使用 .NET 3.5 您还可以使用 SelectConstructor 方法指定它:

var container = new Container(x =>
{
  x.SelectConstructor<NHRepository>(()=>new NHRepository());
});

最后,我确信您可以在 StructureMap 的 XML 配置中定义它,但我没有使用过。您可以对其进行一些搜索。有关上述方法的更多信息,请参见:http ://structuremap.sourceforge.net/ConstructorAndSetterInjection.htm#section3

于 2009-07-02T11:19:36.533 回答
1

所以为 Razzie +1,因为如果 NHRepository 在我自己的程序集中,这将起作用,而是我选择用我自己的 Repository 包装 NHRepository,如下所示..

public class Repository<T> : NHRepository<T>
{
    [DefaultConstructor]
    public Repository()
    {

    }

    public Repository(ISession session)
    {

    }
}

ForRequestedType(typeof (IRepository<>))
                .TheDefaultIsConcreteType(typeof (Repository<>));
于 2009-07-02T11:31:36.073 回答