代码之家  ›  专栏  ›  技术社区  ›  superlogical

结构图-我不想使用最贪婪的构造函数!

  •  7
  • superlogical  · 技术社区  · 16 年前

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

     public class NHRepository<TEntity> : RepositoryBase<TEntity>
     {
    
        public NHRepository () {}
    
    
        public NHRepository(ISession session)
        {
            _privateSession = session; 
        }
    
        ...
    }
    

    我的结构图配置

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

    干杯 满意的

    2 回复  |  直到 16 年前
        1
  •  8
  •   Razzie    16 年前

    您可以设置 [DefaultConstructor] 您希望作为默认值的构造函数的属性。在您的情况下,将其设置为 NHRepository()

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

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

    http://structuremap.sourceforge.net/ConstructorAndSetterInjection.htm#section3

        2
  •  1
  •   superlogical    16 年前

    所以对于Razzie来说+1,因为如果NHRepository在我自己的程序集中,这将起作用,相反,我选择用我自己的存储库包装NHRepository,如下所示。。

    public class Repository<T> : NHRepository<T>
    {
        [DefaultConstructor]
        public Repository()
        {
    
        }
    
        public Repository(ISession session)
        {
    
        }
    }
    
    ForRequestedType(typeof (IRepository<>))
                    .TheDefaultIsConcreteType(typeof (Repository<>));