asp.net MVC2 初探十一

本节介绍如何实现将controller加载进spring容器。首先我们看看配置文件,我就以我做的例子来进行说明先看webConfig,在configuration节点下配置以下内容
< configSections >
         < sectionGroup name ="spring" >
             < section name ="context" type ="Spring.Context.Support.WebContextHandler, Spring.Web" />
             < section name ="objects" type ="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
         </ sectionGroup >
         < section name ="SpringOverrideProperty" type ="System.Configuration.NameValueSectionHandler" />
         < section name ="nhibernate" type ="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
     </ configSections >
     < spring >
         < context >
             < resource uri ="config://spring/objects" />
             < resource uri ="assembly://SpringDao/SpringDao/spring_hibernate_dao.xml" />
             < resource uri ="assembly://SpringDao/SpringDao/Controller.xml" > </ resource >
         </ context >
         < objects xmlns ="http://www.springframework.net" />
     </ spring >
在system.web节点下配置以下内容
< httpModules >
             < add name ="Spring" type ="Spring.Context.Support.WebSupportModule, Spring.Web" />
         </ httpModules >
         < httpHandlers >
             < add verb ="*" path ="*.aspx" type ="Spring.Web.Support.PageHandlerFactory, Spring.Web" />
         </ httpHandlers >
ok,WebConfig配置完成。再看我写的两个xml,第一个Controller.xml
<? xml version ="1.0" encoding ="utf-8" ?>
< objects xmlns ="http://www.springframework.net"
                 xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation ="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd" >
     < object id ="ssCode" type ="Model.SS_CODE,Model" >
         < property name ="C_DATA" value ="2" > </ property >
     </ object >
     < object id ="CodeController" type ="Controllers.CodeController,NormalUniversity" singleton ="false"     autowire ="byName" >
         < property     name ="ssCode" ref ="ssCode" > </ property >
     </ object >
</ objects >
这个文件配置的是Spring要加载进容器的Controller。以及controller中的类( Controllers.CodeController,NormalUniversity,其中Controllers.CodeController是命名空间.类名,NormalUniversity是程序集名称),以及类中的属性。下面是spring_hibernate_dao.xml
<? xml version ="1.0" encoding ="utf-8" ?>
< objects xmlns ="http://www.springframework.net"
                 xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation ="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd" >

     < object id ="DbProvider" type ="SpringDao.SQLProvider, SpringDao" >
         < property name ="ConnectionString" value ="server=.\sql2k5;uid=sa;pwd=sa123;database=test;" />
     </ object >

     < object id ="SessionFactory" type ="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12" >
         < property name ="DbProvider" ref ="DbProvider" />
         < property name ="MappingAssemblies" >
             < list >
                 < value >Model </ value >
             </ list >
         </ property >
         < property name ="HibernateProperties" >
             < dictionary >
                 < entry key ="hibernate.connection.provider" value ="NHibernate.Connection.DriverConnectionProvider" />
                 < entry key ="hibernate.dialect" value ="NHibernate.Dialect.MsSql2005Dialect" />
                 < entry key ="hibernate.connection.driver_class" value ="NHibernate.Driver.SqlClientDriver" />
                 < entry key ="show_sql" value ="true" />
             </ dictionary >
         </ property >
     </ object >

     < object id ="HibernateTransactionManager" type ="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12" >
         < property name ="DbProvider" ref ="DbProvider" />
         < property name ="sessionFactory" ref ="sessionFactory" />
     </ object >

     < object id ="TransactionInterceptor" type ="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data" >
         < property name ="TransactionManager" ref ="HibernateTransactionManager" />
         < property name ="TransactionAttributeSource" >
             < object type ="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data" />
         </ property >
     </ object >
     < object id ="DaoHelper" type ="Dao.SS_CodeDao,Dao" >
         < property name ="sessionFactory" ref ="sessionFactory" />
     </ object >

</ objects >
配置了Spring的工厂,拦截器,事务。以及我写的一个Dao类。要实现controller的加载,必须写一个自定义的ControllerFactory实现IControllerFactory接口。代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
namespace SpringDao
{
         public class ControllerFactory : IControllerFactory
        {
                 private static DefaultControllerFactory defalutf = null;

                 public IController CreateController(RequestContext requestContext, string controllerName)
                {
                         string controller = controllerName + "Controller";
                    
                        IApplicationContext ctx = Container.GetContext();
                         if (ctx.ContainsObject(controller))
                        {
                                 object controllerf = ctx.GetObject(controller);
                                 return (IController)controllerf;
                        }
                         else
                        {
                                 if (defalutf == null)
                                {
                                        defalutf = new DefaultControllerFactory();
                                }

                                 return defalutf.CreateController(requestContext, controllerName);
                        }
                }

                 public void ReleaseController(IController controller)
                {
                        IApplicationContext ctx = Container.GetContext();

                         if (!ctx.ContainsObject(controller.GetType().Name))
                        {
                                 if (defalutf == null)
                                {
                                        defalutf = new DefaultControllerFactory();
                                }

                                defalutf.ReleaseController(controller);
                        }
                }

        }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using System.Collections;
namespace SpringDao
{
         public class Container
        {
                 /// <summary>
                 /// 获取应用程序上下文.
                 /// </summary>
                 /// <returns><see cref="IApplicationContext"/>应用程序上下文.</returns>
                 public static IApplicationContext GetContext()
                {
                         if (FApplicationContext == null)
                        {
                                FApplicationContext = ContextRegistry.GetContext();
                        }
                         return FApplicationContext;
                }

                 /// <summary>
                 /// 获取应用程序上下文.
                 /// </summary>
                 /// <param name="name"><see cref="IApplicationContext"/>应用程序上下文名称.</param>
                 /// <returns><see cref="IApplicationContext"/>应用程序上下文.</returns>
                 public static IApplicationContext GetContext( string name)
                {
                         return ContextRegistry.GetContext(name);
                }

                 /// <summary>
                 /// 获取对象.
                 /// </summary>
                 /// <typeparam name="T">对象的类型.</typeparam>
                 /// <param name="id">标识.</param>
                 /// <returns></returns>
                 public static T GetObject<T>( string id)
                {
                         return (T)GetContext().GetObject(id);
                }

                 /// <summary>
                 /// 获取对象类表.
                 /// </summary>
                 /// <typeparam name="T">对象的类型.</typeparam>
                 /// <returns></returns>
                 public static IList<T> GetObjects<T>()
                {
                        IEnumerable items = GetContext().GetObjectsOfType( typeof(T));
                        IList<T> objects = new List<T>();
                         foreach (DictionaryEntry item in items)
                        {
                                objects.Add((T)item.Value);
                        }
                         return objects;
                }

                [ThreadStatic]
                 private static IApplicationContext FApplicationContext;

        }
}
这些代码是我从网上直接copy的,直接拿来用。完了之后我们要把controller的工厂重新指定到我们自定义的工厂。
在Global.asax的Application_Start()方法中,加入以下代码
ControllerBuilder.Current.SetControllerFactory( typeof(SpringDao.ControllerFactory));
然后再看看我们的controller
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using NHibernate.Expression;
namespace Controllers
{
         public class CodeController : BaseController<SS_CODE>
        {
                 private SS_CODE ssCode { set; get; }

                 public ActionResult Index()
                {
                        ssCode.C_DATA = "aaaa";
                         return base.Index1( "~/Views/System/Code/Index.aspx");
                }
        }
}
在这里我们不用实例化SS_CODE 就可以直接使用其对象。最后讲一下Log4Net。用于在客户端写入日志,配置如下
<? xml version ="1.0" encoding ="utf-8" ?>
< log4net >
     < logger name ="WebLogger" >
         < level Value ="DEBUG" > </ level >
         < appender-ref ref ="LogFileAppender" />
         < appender-ref ref ="RollingLogFileAppender" > </ appender-ref >
     </ logger >
     < appender name ="RollingLogFileAppender" type ="log4net.Appender.RollingFileAppender" >
        <!-- 日志文件名开头-->
         < file value ="App_Data\\Log.txt" />
        <!-- 是否追加到文件-->
         < appendToFile value ="true" />
        <!-- 混合使用日期和文件大小变换日志文件名-->
         < rollingStyle value ="Composite" />
        <!-- 日期的格式-->
         < datePattern value ="yyyyMMdd" />
        <!-- 最大变换数量-->
         < maxSizeRollBackups value ="10" />
        <!-- 最大文件大小-->
         < maximumFileSize value ="1MB" />
         < layout type ="log4net.Layout.PatternLayout" >
             < conversionPattern value ="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
         </ layout >
     </ appender >
</ log4net >
然后新建一个txt如下
打开Assembly,加入
[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"App_Data\Log4Net.Config.xml", Watch = true)]
在web.config configSections加入以下下配置
< section name ="log4net" type ="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
controller中的代码
ILog lg = log4net.LogManager.GetLogger( "WebLogger");
                        {
                                 if (lg.IsErrorEnabled)
                                {
                                        lg.Error( this.GetType().ToString()+ "xxxx李磊");
                                        
                                }
                        }
我们发现不能写入汉字,晕啊
怎么办呢?找了好久,我才找到这个办法。首先我们把Log4Net.dll给反射出来
反射到F盘下,我们看看反射的程序集
我们展开log4net\Util,打开Transform.cs,注释掉private static Regex INVALIDCHARS哪一行,重新编译生成dll,就可以写入汉字了。
有什么问题联系我QQ:316575647

你可能感兴趣的:(职场,asp.net,MVC2,休闲)