2011-08-22 116 views
0

我很新(即一个小时左右)NHibernate。我遵循的教程给了我以下类:我可以在NHibernate中将参数传递给ISessionFactory吗?

public class ContactNHibernateHelper 
{ 
    private static ISessionFactory _sessionFactory; 

    private static ISessionFactory SessionFactory 
    { 
     get 
     { 
      if (_sessionFactory == null) 
      { 
       var configuration = new Configuration(); 
       configuration.Configure(); 
       configuration.AddAssembly(typeof (CRMData.Objects.Contact).Assembly); 
       _sessionFactory = configuration.Configure().BuildSessionFactory(); 
      } 
      return _sessionFactory; 
     } 
    } 

    public static ISession OpenSession() 
    { 
     return SessionFactory.OpenSession(); 
    } 
} 

在扩展我的应用程序,我现在有一个不同的对象的另一个类。我试图重写上面的类,以便我可以传入组件类型作为参数并返回_sessionFactory。所以,例如,我将有一个变量传递给名为assembly的方法。然后,该代码将是:

public class GenericNHibernateHelper 
{ 
    private static ISessionFactory _sessionFactory; 

    private static ISessionFactory SessionFactory(System.Reflection.Assembly assembly) 
    { 
     get 
     { 
      if (_sessionFactory == null) 
      { 
       var configuration = new Configuration(); 
       configuration.Configure(); 
       configuration.AddAssembly(assembly); 
       _sessionFactory = configuration.Configure().BuildSessionFactory(); 
      } 
      return _sessionFactory; 
     } 
    } 
} 

这是给错误“无法解析符号‘GET’” - 大概是因为我不能用这种方式传递任何参数。

我可能错过了很简单的东西 - 任何想法?

回答

1

如果您的其他类与CRMData.Objects.Contact在同一个程序集中,则不需要进行任何更改。

但是,如果您想传入参数,则需要将SessionFactory属性转换为方法或创建接受该参数的构造函数。

private static ISessionFactory SessionFactory(System.Reflection.Assembly assembly) 
{ 
    if (_sessionFactory == null) 
    { 
     var configuration = new Configuration(); 
     configuration.Configure(); 
     configuration.AddAssembly(assembly); 
     _sessionFactory = configuration.Configure().BuildSessionFactory(); 
    } 
    return _sessionFactory; 
} 
+0

工作 - 编程时我有点“绿色”,所以虽然这工作,但我不知道为什么!非常感谢。 –

+0

这个代码的唯一问题是,如果多次调用SessionFactory方法,“assembly”参数将不会被考虑在内。 –

+0

@Dmitry - 你可以扩展吗?这是否与“静态”限定符有关?我还没有弄清楚静态是什么。 –

0

我们在C#中除了索引器之外没有参数属性。这就是你得到错误的原因。改变你的代码使用方法。

但我仍然不明白你为什么需要将一个程序集传递给该方法。

+0

我试图创建节省了我不必创建一个全新的类我想基于不同的组件(CRMData.Objects.Contact,CRMData.Objects创建一个新的ISessionFactory每次的通用方法。帐户,CRMData.Objects.Staff,CRMData.Objects.etc ...) –

相关问题