asp.net MVC2 初探十一
生活随笔
收集整理的這篇文章主要介紹了
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
????????<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
轉載于:https://blog.51cto.com/leelei/326473
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的asp.net MVC2 初探十一的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Javascript的调试利器:Fire
- 下一篇: 3G时代手机网站的特点和开发原则