csharp: Configuring ASP.NET with Spring.NET and FluentNHibernate

来源:http://www.cnblogs.com/geovindu/archive/2017/06/26/7079309.html
-Advertisement-
Play Games

Domain: FluentNhibernateLocalSessionFactoryObject.cs Dao:dataAccess.xml NHibernate 配置 Dao:objects.xml Service:objects.xml FluentNHibernateSpingNetDemo ...


Domain: FluentNhibernateLocalSessionFactoryObject.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate;
using NHibernate.Cfg;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions.Helpers;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Reflection;
using FluentNHibernate;
using NHibernate.Tool.hbm2ddl;
using NHibernate;


namespace Geovin.Du.Domain
{
    /// <summary>
    /// 塗聚文20170623
    /// </summary>
    public class FluentNhibernateLocalSessionFactoryObject : LocalSessionFactoryObject
    {
        ///// <summary>
        ///// Sets the assemblies to load that contain fluent nhibernate mappings.
        ///// </summary>
        ///// <value>The mapping assemblies.</value>
        //public string[] FluentNhibernateMappingAssemblies {
        //    get;
        //    set;
        //}MySQLConfiguration.Standard

        public string[] FluentNhibernateMappingAssemblies { get; set; }
        public string ConnectionStringName { get; set; }
        static readonly object factorylock = new object();

        protected override void PostProcessConfiguration(Configuration config)
        {
            ConnectionStringName = "Server=GEOVINDU-PC;Database=DuMailSystem;User ID=sa;Password=塗聚文";
            base.PostProcessConfiguration(config);
            FluentConfiguration fluentConfig = Fluently.Configure(config)
                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnectionStringName)) //MsSql2005 MsSql2012 
                .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true));
            Array.ForEach(FluentNhibernateMappingAssemblies,
                           assembly => fluentConfig.Mappings(
                                                    m => m.FluentMappings.AddFromAssembly(Assembly.Load(assembly))
                                                        .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never())
                                                    )
                         );
            fluentConfig.BuildSessionFactory();
        }
    } //class
}

  Dao:dataAccess.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database" xmlns:tx="http://www.springframework.net/tx">
  <!--描述-->
  <description>
    數據訪問的配置信息
    包括:DbProvider
    NHibernate
  </description>

  <!-- 通過主應用程式的上下文配置文件引用 -->
  <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
    <property name="ConfigSections" value="spring/databaseSettings"/>
  </object>

  <!-- 資料庫的配置-->
  <db:provider id="DbProvider"
                   provider="SqlServer-2.0"
                   connectionString="Server=${db.server};Database=${db.database};User ID=${db.userid};Password=${db.password}"
               />

  <!-- Fluent NHibernate 配置  塗聚文 Geovin Du-->

	<!-- 可以通過 name 為其指定別名 name="SessionFactory" -->
	<object id="NHibernateSessionFactory" type="Geovin.Du.Domain.FluentNhibernateLocalSessionFactoryObject, Domain">
		<!--關於資料庫連接的配置,直接使用 DbProvider 中的設置,這樣,不需要為 Hibernate 再提供連接串和驅動-->
		<property name="DbProvider" ref="DbProvider"/>
		<!--包含有映射文件的程式集,需要分析的hbm程式集名稱-->
		<property name="FluentNhibernateMappingAssemblies">
			<list>
				<value>Domain</value>
			</list>
		</property>
		<!--其他的參數-->
		<property name="HibernateProperties">
			<dictionary>
				<!--方言MsSql2005Dialect-->
				<entry key="dialect" value="NHibernate.Dialect.MsSql2012Dialect"/>
				<entry key="use_proxy_validator" value="false" />
				<entry key="show_sql" value="true"/>
			</dictionary>
		</property>
		<!--必須增加此項說明,與 Spring 的聲明式事務集成-->
		<property name="ExposeTransactionAwareSessionFactory" value="true" />
	</object>

  NHibernate 配置

<!-- NHibernate 配置 塗聚文 Geovin Du -->
 
<!-- 可以通過 name 為其指定別名 name="SessionFactory" -->
  <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject,Spring.Data.NHibernate4">
     <!--關於資料庫連接的配置,直接使用 DbProvider 中的設置,這樣,不需要為 Hibernate 再提供連接串和驅動-->
    <property name="DbProvider" ref="DbProvider"/>
     <!--包含有映射文件的程式集,需要分析的hbm程式集名稱-->
    <property name="MappingAssemblies">
      <list>
        <value>Domain</value>
      </list>
    </property>
     <!--其他的參數-->
    <property name="HibernateProperties">
      <dictionary>
         <!--方言-->
        <entry key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
        <entry key="use_proxy_validator" value="false" />
        <entry key="show_sql" value="true"/>
      </dictionary>
    </property>
     <!--必須增加此項說明,與 Spring 的聲明式事務集成-->
    <property name="ExposeTransactionAwareSessionFactory" value="true" />
  </object>

  Dao:objects.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object id="CustomerDaoImpl" type="Geovin.Du.Dao.CustomerDao,Dao">
     <!--ref 表示引用的對象--> 
    <property name="SessionFactory" ref="NHibernateSessionFactory"  />
  </object>

  <object id="SendMailDaoImpl" type=" Geovin.Du.Dao.SendMailDao,Dao">
    <!--ref 表示引用的對象-->
    <property name="SessionFactory" ref="NHibernateSessionFactory"  />
  </object>


</objects>

  Service:objects.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object id="CustomerServiceImpl" type="Geovin.Du.Service.CustomerService"    >
     <!--ref 表示引用的對象--> 
    <property name="CustomerDao" ref="CustomerDaoImpl"  />
  </object>
  <object id="SendMailServiceImpl" type="Geovin.Du.Service.SendMailService">
    <!--ref 表示引用的對象-->
    <property name="SendMailDao" ref="SendMailDaoImpl"  />
  </object>
</objects>

  FluentNHibernateSpingNetDemo:objects.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object id="framework" type="FluentNHibernateSpingNetDemo.Framework">
    <property name="Name" value="Spring.NET"/>
  </object>

  <!-- 頁面對象 -->
  <object type="~/Default.aspx">
    <!-- ref 表示引用的對象 -->
    <property name="Framework" ref="framework"/>
  </object>

  <object type="~/Customer/index.aspx">
    <property name="CustomerService" ref="CustomerServiceImpl"/>
  </object>

  <object type="~/Send/index.aspx">
    <property name="SendMailService" ref="SendMailServiceImpl"/>
  </object>
</objects>

  FluentNHibernateSpingNetDemo:Web.config

<?xml version="1.0"?>

<!--
  有關如何配置 ASP.NET 應用程式的詳細信息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <configSections>
    <!-- Spring 的配置 -->
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>

      <!-- 資料庫的配置參數 -->
      <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>

    <!-- 日誌配置 -->
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
  </configSections>
	<connectionStrings>
		<add name="SqlConnection" connectionString="Server=GEOVINDU-PC;Database=DuMailSystem;User ID=sa;Password=770214" providerName="System.Data.SqlClient"/>
		<add name="SqlRole" connectionString="dbo"/>
		<!--<add name="SqlConnection" connectionString="Server=124.172.156.191;Database=dupcitgeovindu;User ID=dupcitgeovindu_f;Password=lf770214;"  providerName="System.Data.SqlClient"/>
    <add name="SqlRole" connectionString="dupcitgeovindu_f"/>-->
	</connectionStrings>
  <spring>
    <context>
      <resource uri="~/Config/objects.xml"/>

      <!-- 嵌入在程式集中的配置文件 ,首先是程式集名稱,然後命名空間,最後文件名, 註意名稱的大小寫必須完全一致 -->
      <resource uri="assembly://Dao/Dao.Config/dataAccess.xml"/>
      <resource uri="assembly://Dao/Dao.Config/objects.xml"/>
      <resource uri="assembly://Service/Service.Config/objects.xml"/>
    </context>

    <!--資料庫配置伺服器地址-->
    <databaseSettings>
      <add key="db.server" value="GEOVINDU-PC"/>
      <add key="db.database" value="DuMailSystem"/>
      <add key="db.userid" value="塗聚文"/>
      <add key="db.password" value="塗聚文"/>
    </databaseSettings>
  </spring>

  <!--<common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
         使用 log4net 配置文件 
        <arg key="configType" value="FILE-WATCH" />
        <arg key="configFile" value="~/Config/log4net.xml" />
      </factoryAdapter>
    </logging>
  </common>-->

  <appSettings>
    <!-- 為 OpenSessionInViewModule 的 SessionFactory 提供名字 -->
    <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="NHibernateSessionFactory"/>
  </appSettings>
  
  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <!--<authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>-->
    <httpModules>
      <!-- Spring 提供的 Module  -->
      <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>

      <!-- 
          由 Spring 自動打開會話,必須提供一個名為 SessionFactory 的會話工廠 
          使用後,可以使用 SessionFactory 的 GetCurrentSession 方法獲取會話
      -->
      <add name="OpenSessionInView"
           type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate4"/>
    </httpModules>
    <httpHandlers>
      <!-- Spring 提供的處理程式 -->
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
      <!-- 取消 Spring.NET 對於 Web 服務的處理 -->
      <!--<add verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web"/>-->
      <add verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor, Spring.Web"/>
      <add verb="*" path="*.ashx" type="Spring.Web.Support.DefaultHandlerFactory, Spring.Web"/>
    </httpHandlers>
    <!--<membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>-->

  </system.web>

  <!--<system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>-->
</configuration>

  http://blog.bennymichielsen.be/2009/01/04/using-fluent-nhibernate-in-spring-net/

protected override void PostProcessConfiguration(Configuration config)
{
base.PostProcessConfiguration(config);
Fluently.Configure(config)
.Database(MySQLConfiguration.Standard.ConnectionString(
c => c.FromConnectionStringWithKey(“connectionString”)))
.Mappings( m => m.FluentMappings
.AddFromAssemblyOf())
.BuildSessionFactory();
}

 

 

 

protected override ISessionFactory NewSessionFactory(Configuration config)
{
config = Fluently.Configure(config)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf())
.BuildConfiguration();
return base.NewSessionFactory(config);
}
 

here is the implementation if you are using FluentNhibernate auto mapping :
protected override void PostProcessConfiguration(Configuration config)
{
base.PostProcessConfiguration(config);

var autoMappingCfg = new AutoMappingConfiguration();

var autoMap = AutoMap.AssemblyOf(autoMappingCfg)
.Conventions.Add(DefaultCascade.All(), DefaultLazy.Never())
.Conventions.Add()
.Override(map => { map.IgnoreProperty(i => i.Total); });

Fluently.Configure(config)
.Mappings(m => m.AutoMappings.Add(autoMap))
.BuildConfiguration();
}

in outmapping you don’t need to inject FluentNhibernateMappingAssemblies. so configure Sping.Net accordingly

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate;
using FluentNHibernate;
using System.Reflection;
using NHibernate.Cfg;
 
namespace SessionFactories
{
    public class FluentNhibernateLocalSessionFactoryObject
    : LocalSessionFactoryObject
    {
        /// <summary>
        /// Sets the assemblies to load that contain fluent nhibernate mappings.
        /// </summary>
        /// <value>The mapping assemblies.</value>
        public string[] FluentNhibernateMappingAssemblies
        {
            get;
            set;
        }
 
        protected override void PostProcessConfiguration(Configuration config)
        {
            base.PostProcessConfiguration(config);
            if(FluentNhibernateMappingAssemblies != null)
            {
                foreach(string assemblyName in FluentNhibernateMappingAssemblies)
                {
                    config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
                }
            }
        }
    }
}
 

  

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 作者:Antonio Leiva 時間:Jun 20, 2017 原文鏈接:https://antonioleiva.com/objects-kotlin/ Kotlin對象是Android開發人員不熟悉的另一個語言元素,因為在Java中沒有這樣的東西。 事實上,對象就是具有單一實現的數據類型。所以 ...
  • 以下代碼是一個顯示圖片的RecyclerView 的Adapter用到的,當點擊圖片,跳到另一個Activity顯示大圖。RecyclerView 與ListView不同 然而沒有setOnClickListener() 方法, 設置事件監聽, 使用下麵的方式。點擊後獲取到圖片url 傳遞給另一個a ...
  • 場景描述 誤 drop 了生產庫中的用戶 U1 U1 用戶下麵有 3 張表(T1 T3),表中數據如下所示: 前期準備 第一步,查詢 v$log、v$archived_log中每個日誌的 First SCN/ First Time 和 Next SCN/Next Time,根據時間推測該刪除操作會在 ...
  • 第6節 文件打包與解壓縮 《Linux 基礎入門(新版)》學習筆記 ...
  • 一,引入dll 1.ServiceStack.Common.dll 2.ServiceStack.Interfaces.dll 3.ServiceStack.Redis.dll 4.ServiceStack.Text.dll 二,修改配置文件 在你的配置文件中加入如下的代碼: <appSetting ...
  • 示例代碼: PT_USER_INFO user = new PT_USER_INFO(); IList<TES_COMBAT_TASK> taskList = new List<TES_COMBAT_TASK>(); BackgroundWorker worker = new BackgroundW ...
  • 機器人發展至今技術可以說算得上非常成熟了,近日有新聞報導稱,高仿機器人有了自己的獨立思想,可以自由的與人通話,分辨談話內容,知道如何接話,並且也有豐富的面部表情,雖然看起來極不自然,但至少說明瞭這項技術目前的技術水平又達到了一個新高度,未來是否大力研發量產這些機器人是值得深思的問題,電影里也有演到未 ...
  • 1.新建控制台程式。 2.添加Log4Net nuget 3.添加MySql 引用 4.添加配置文件如下: <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Con ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...