NHibernate.Cfg.Configuration的一个实例代表了应用程序中所有的.NET类到SQL数据库的映射的集合。Configuration用于构造一个(不可变的)ISessionFactory。这些映射是从一些XML映射文件中编译得来的。
你可以得到一个Configuration的实例,直接实例化它即可。下面有一个例子,用来从两个XML配置文件(和exe文件在同一个目录下)中的映射中初始化:
Configuration cfg = new Configuration()
.AddXmlFile("Item.hbm.xml")
.AddXmlFile("Bid.hbm.xml");
另外一个(某些时候更好的)方法是让NHibernate自行用GetManifestResourceStream()来装载映射文件
Configuration cfg = new Configuration()
.AddClass( typeof(NHibernate.Auction.Item) )
.AddClass( typeof(NHibernate.Auction.Bid) );
NHibernate 就会在这些类型的程序集的嵌入的资源中寻找叫做NHibernate.Auction.Item.hbm.xml 和 NHibernate.Auction.Bid.hbm.xml的映射文件。这种方法取消了所有对文件名的硬编码。
另外一个(可能是最好的)方法是让NHibernate读取一个程序集中所有的配置文件:
Configuration cfg = new Configuration()
.AddAssembly( "NHibernate.Auction" );
NHibernate将会遍历程序集查找任何以hbm.xml结尾的文件。 这种方法取消了所有对文件名的硬编码并且确保程序集中的配置文件文件都会被加载。
在使用VisualStudio.NET或者NAnt生成程序集时请确保hbm.xml文件是作为嵌入资源(Embedded Resources)添加的。
Configuration也可以指定一些可选的配置项
Hashtable props = new Hashtable();
...
Configuration cfg = new Configuration()
.AddClass( typeof(NHibernate.Auction.Item) )
.AddClass( typeof(NHibernate.Auction.Bid) );
cfg.Properties = props;
Configuration是仅在配置期使用的对象,从第一个SessionFactory开始建立的时候,它就失效了。
顶部