Castle ActiveRecord 使用 Web.config 配置数据库连接方式

相关文章:《Castle ActiveRecord 使用内嵌的配置文件

使用把 XML 配置文件作为内嵌资源编译进 ASP.NET DLL 方式的优点是最大限度保护了数据库连接字符串的安全性。然而,缺点也十分明显,就是无法手动编辑数据库连接字符串,这很大程度上给部署维护带来了麻烦。

把数据库连接方式写进 Web.config 是最自然的做法了。

一. 示例 C# 代码 (.NET 1.1)

using  System;
using  NUnit.Framework;

using  test;

using  System.Reflection;

using  Castle.ActiveRecord.Framework.Config;
using  Castle.ActiveRecord;

namespace  test._TestUnitCase
{
    
/**/ ///   <summary>
    
///  BlogTest 的摘要说明。
    
///   </summary>
    [TestFixture]
    
public   class  BlogTest
    {
        
public  BlogTest()
        {
        }
        
        [Test]
        
public   void  CreateBlogTest()
        {
            Assembly assembly 
=   typeof (test.Blog).Assembly;
            IConfigurationSource src
=  System.Configuration.ConfigurationSettings.GetConfig( " activerecord " as  IConfigurationSource;
            ActiveRecordStarter.Initialize( src, 
typeof (Blog) );


            Blog blog 
=   new  Blog();

            blog.Name
= " abcde1234 " ;
            blog.Author
= " stephenabcdef " ;
            
            Console.WriteLine(BlogManager.getInstance().CreateBlog(blog));
        }
    }
}

备注:

.NET 2.0 的写法是,把 IConfigurationSource src = ...... 一行替换为如下代码:

IConfigurationSource src  =  System.Configuration. ConfigurationManager.GetSection ( " activerecord " as  IConfigurationSource;

二. Web.config 的配置

<? xml version="1.0" encoding="utf-8"  ?>
< configuration >

    
< configSections >

        
< section  name ="activerecord"  type ="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"   />

    
</ configSections >

    
< activerecord >
        
< config >

            
< add  key ="hibernate.connection.driver_class"  value ="NHibernate.Driver.SqlClientDriver"   />
            
< add  key ="hibernate.dialect"  value ="NHibernate.Dialect.MsSql2000Dialect"   />
            
< add  key ="hibernate.connection.provider"  value ="NHibernate.Connection.DriverConnectionProvider"   />
            
< add  key ="hibernate.connection.connection_string"  value ="UID=sa;Password=sa;Initial Catalog=ARDemo;Data Source=."   />
        
</ config >
    
</ activerecord >

</ configuration >

你可能感兴趣的:(ActiveRecord)