net的app.config程序配置Spring.net和nhibernate

6 篇文章 0 订阅
4 篇文章 0 订阅
<?xml version="1.0"?>
<configuration> 
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821"/>
        <sectionGroup name="spring">
            <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" />
            <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
    </configSections>

    <spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>
        <parsers>
            <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data" />
            <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
        </parsers>

        <objects xmlns="http://www.springframework.net"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:tx="http://www.springframework.net/tx"
             xmlns:db="http://www.springframework.net/database">

            <db:provider id="DbProvider"
                           provider="SqlServer-2.0"
                           connectionString="Data Source=CHETUIWK123\SQL2008R2;Integrated Security=true;Database=TestNhibernate;"/>
            <object id="MySessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate33">
                <property name="ExposeTransactionAwareSessionFactory" value="true" />
                <property name="DbProvider" ref="DbProvider"/>
                <property name="MappingAssemblies">
                    <list>
                        <value>BlackOpsP2.Core</value>
                    </list>
                </property>
                <property name="HibernateProperties">
                    <dictionary>

                        <entry key="hibernate.connection.provider"
                               value="NHibernate.Connection.DriverConnectionProvider"/>

                        <entry key="dialect"
                               value="NHibernate.Dialect.MsSql2008Dialect"/>

                        <entry key="hibernate.connection.driver_class"
                               value="NHibernate.Driver.SqlClientDriver"/>

                    </dictionary>
                </property>
            </object>

            <object id="HibernateTransactionManager"
            type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate33">
                <property name="SessionFactory" ref="MySessionFactory"/>
            </object>

            <object id="EmployeeDao" xsi:schemaLocation="" type="BlackOpsP2.Data.EmployeeDao, BlackOpsP2.Data">
                <property name="SessionFactory" ref="MySessionFactory"/>
            </object>

            <object id="EmployeeService" type="BlackOpsP2.Services.ARModule.EmployeeService, BlackOpsP2.Services">
                <property name="TransactionManager" ref="HibernateTransactionManager"/>
                <property name="Dao" ref="EmployeeDao"/>
            </object>

            <object id="EmployeeController" type="BlackOpsP2.Presentation.Controller.ARModule.EmployeeController, BlackOpsP2.Presentation">
                <property name="Service" ref="EmployeeService"/>
            </object>

            <!--> manually added -->
            <object id="Form" type="BlackOpsP2.UI.Form1, BlackOpsP2.UI">
                <property name="Controller" ref="EmployeeController"/>
            </object>
            <!--> /****/ -->

            <tx:attribute-driven transaction-manager="HibernateTransactionManager"/>
        </objects>
    </spring>

    <log4net>
        <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
            <file value="E:\Test\log.txt"/>
            <appendToFile value="true"/>
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %level %logger - %message%newline"/>
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <levelMin value="INFO"/>
                <levelMax value="FATAL"/>
            </filter>
        </appender>

        <root>
            <level value="DEBUG"/>
            <appender-ref ref="FileAppender"/>
        </root>
    </log4net>
</configuration>

一、打开vs2010,菜单文件->新建->项目->其它项目类型->vs解决方案

工程结构分部:

       Solution-

                     src

                          Domain

                                        Entities

                                        Mappings

                          Dao

                                        Config

                                        Interface

                                        InterfaceImpl

                          Nhibernate(这一层可以不写用上面的)

                                        Nhibernate

                          Service

                                        Interface

                                        InterfaceImpl                                       

                          Winform工程

                     lib

                     doc

1、新建一个类库工程domain,位置路径为解决方案路径下面的src下面。

vs工程新建的时候必须看下工程的属性必须选择 .net framework 4 默认是client这个有问题。使用spring.net和nhibernate时候报引用错误

 

2、在Domain工程下新建2个文件夹Entities和Mappings,然后使用自动生成工具生成entities和mappings文件并添加进vs2010对应工程文件夹,因为用了动软生成实体,和codesmith生成配置文件所以生成的文件名字、字段属性可能不一致,这里需要修改一下。

 用到mapping的时候配置文件必须是嵌入式的否则会报错

Error creating context 'spring.root': InputStream is null from Resource = [assembly [Dao, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [Dao.Dao.Config.Dao.xml]]

 

3、再次新建类库工程Dao(Service)下面新建2个文件夹Dao、DaoImpl(Service、ServiceImpl)。添加对应的业务接口可实现。

4、添加form工程WinForm  添加Form文件夹,编写Form程序

Form 程序入口添加log4net 加载。也可以把form 交给spring.net管理(不推荐)

第一步:在项目中添加对log4net.dll

第二步:程序启动时读取log4net的配置文件。

如果是CS程序,在根目录的Program.cs中的Main方法中添加:

log4net.Config.XmlConfigurator.Configure();

如果是BS程序,在根目录的Global.asax.cs(没有新建一个)中的Application_Start方法中添加:

log4net.Config.XmlConfigurator.Configure();

无论BS还是CS程序都可直接在项目的AssemblyInfo.cs文件里添加以下的语句:

[assembly: log4net.Config .XmlConfigurator()]

 static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //读取log4net配置文件
            log4net.Config.XmlConfigurator.Configure(); 

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
          

            //IApplicationContext ctx = ContextRegistry.GetContext();
            //Form1 from1 = (Form1)ctx.GetObject("Form1");
            //Application.Run(from1);
        }
    }

form表单程序

private void button1_Click(object sender, EventArgs e)
        {
            // create and configure objects
            //IApplicationContext ctx = new XmlApplicationContext("assembly://Dao/Dao.Config/Dao.xml", "assembly://Service/Service.Config/Service.xml");

            IApplicationContext ctx = ContextRegistry.GetContext();
            IProductService productService = ctx.GetObject("ProductService") as IProductService;
            productService.ProcessProduct();
        }


 

二、配置app.config

1、在WinForm工程中添加app.config xml配置文件

<?xml version="1.0"?>
<configuration>
  <!--加载需要用到的配置文件-->
  <configSections>
    <!--Spring 配置节点id-->
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
      <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    </sectionGroup>
    
    <!--Log4net 日志配置节点id-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    <!--数据库配置节点id-->
    <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <!--Spring 配置节点id对应具体的配置文件位置3种读法-->
  <spring>
    <context>
      <!--第一种App.config 在Context配置节中作如下指示-->
      <resource uri="config://spring/objects"/>
      <!--第二种最常用 读取嵌入在程序集中的配置文件 ,首先是解决方案下的类库的程序集名称,然后解决方案下面的项目名+项目配置文件路径,注意名称的大小写必须完全一致 -->
      <!--Dao-->
      <resource uri="assembly://Dao/Dao.Config/Dao.xml"/>
      <resource uri="assembly://Service/Service.Config/Service.xml"/>
      <!-- 第三种从文件目录位置读取配置文件-->
      <!--<resource uri="file://D:/SvnProject/NetProjectDemo/Spring.Nhibernate.App/src/WinForm/Service.xml"/>-->
    </context>
    <parsers>
      <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
      <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
    </parsers>
    <!--第一种就是把Dao.xml的内容贴到这里App.config 在Context配置节中作如下指示-->
    <objects xmlns="http://www.springframework.net">
      <description>An  example that demonstrates simple IoC features.</description>
      <!--<object id="Form1" type="WinForm.Form1">-->
      <!--</object>-->
    </objects>

  </spring>
  <!-- These properties are referenced in Dao.xml -->
  <databaseSettings>
    <add key="db.datasource" value="127.0.0.1"/>
    <add key="db.user" value="root"/>
    <add key="db.password" value=""/>
    <add key="db.database" value="kasai"/>
  </databaseSettings>

 

  <!--log4net 配置节点id对应具体的配置文件位置-->
  <log4net>
    <!--控制台输出日志-->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <!--文件日志输出-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="Logs/Log.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="10" />
      <param name="MaximumFileSize" value="10MB" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <param name="datePattern" value="yyyy-MM-dd HH:mm" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
      </layout>
    </appender>

     <!--默认日志输出级别根节点,其它没有写的话都继承这个Set default logging level to DEBUG--> 
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>

     <!--设置其他插件日志输出Set logging for Spring.  Logger names in Spring correspond to the namespace--> 
    <logger name="Spring">
      <level value="DUBUG"/>
    </logger>

    <logger name="Spring.Data">
      <level value="DUBUG"/>
    </logger>

    <logger name="NHibernate">
      <level value="DUBUG"/>
    </logger>


  </log4net>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

2、Dao.xml配置文件下面红色标注的地方必须注意不同版本可能有所区别,文档上的跟新不是很及时有些东西是老的容易出错。还是要看版本更新列表说明。

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

  <!-- Referenced by main application context configuration file -->
  <description>
    The Northwind object definitions for the Data Access Objects.
  </description>

  <!-- 用以我们在其它的应用程序中,配置数据访问 -->
  <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
    <property name="ConfigSections" value="databaseSettings"/>
  </object>

  <!-- Database Configuration -->
  <db:provider id="DbProvider"
               provider="MySql-5.2.3"
               connectionString="Data Source=127.0.0.1;Database=kasai;User Id=root;Password="/>
  <!--connectionString="Data Source=${db.datasource};Database=${db.database};User Id=${db.user};Password=${db.password};"-->

  <!-- NHibernate Configuration -->
  <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate32">
    <property name="DbProvider" ref="DbProvider"/>
    <property name="MappingAssemblies">
      <list>
        <!--mapping所在程序集-->
        <value>Domain</value>
      </list>
    </property>
    <property name="HibernateProperties">
      <dictionary>
        <!--配置属性不同版本key和value可能都不一样-->
        <entry key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
        <entry key="dialect" value="NHibernate.Dialect.MySQL5Dialect"/>
        <entry key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
        <entry key="use_proxy_validator" value="false" />
      </dictionary>
    </property>

    <!-- provides integation with Spring's declarative transaction management features -->
    <property name="ExposeTransactionAwareSessionFactory" value="true" />

  </object>


  <!-- Transaction Management Strategy - local database transactions -->
  <object id="transactionManager"
        type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate32">

    <property name="DbProvider" ref="DbProvider"/>
    <property name="SessionFactory" ref="NHibernateSessionFactory"/>

  </object>


  <!-- Exception translation object post processor -->
  <!--<object type="Spring.Dao.Attributes.PersistenceExceptionTranslationPostProcessor, Spring.Data"/>-->

  <!-- Data Access Objects -->

  <object id="ProductDao" type="Dao.InterfaceImpl.ProductDao, Dao">
    <property name="SessionFactory" ref="NHibernateSessionFactory"/>
  </object>

</objects>

2.3 Servcie.xml 配置

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

  <!-- Referenced by main application context configuration file -->

  <description>
    The  service layer definitions
  </description>

  <!-- Property placeholder configurer for database settings -->
  <object id="ProductService" type="Service.InterfaceImpl.ProductService, Service">
    <property name="ProductDao" ref="ProductDao"/>
  </object>

  <tx:attribute-driven/>


</objects>




 

 


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值