Go ASP. NET MVC spring.net NHibernate Integration

Source: Internet
Author: User
Tags manual writing

Please specify the reprint address: Http://www.cnblogs.com/arhat

Before the integration of these three technologies, first of all to explain the integration of the steps, as the saying goes, Khan to eat a mouthful, things to do one thing. The same is true of the three technologies. Before you integrate, you need to
Asp.net,spring.net,nhibernate have some knowledge, it is best to have some experience, because for no reason to put 3 technology together, will make small awkward, in fact, like the configuration of chemical drugs, if 3 of raw materials have a little way out, then the whole experiment will fail.

There are many people on the Internet have written similar articles, may be my humble, read a lot of articles have not solved my problem, at the same time I in the process of integration took a lot of detours. Make a note today to prevent yourself from forgetting. Okay, here we are.

Integration principle:

We have studied chemistry in junior high School, we know that some substances are not very good reaction, need to through the catalyst to change the good reaction between the two. So we think of ASP. NET MVC as material a,nhibernate as material c. itself a+c= application. But because the combination of a and C can lead to some development problems (such as the control of the transaction), then what to do, we can add Catalyst spring.net (substance B). This catalyst through B is a good solution to the problem between the a+c. So the formula came out of the a+b+c= application.

Of course, we are programmed here rather than chemically, so in the process of combining we follow the steps below.

1. asp. NET MVC + spring.net

2. asp. NET MVC + NHibernate

3. asp. NET MVC + spring.net +nhibernate
This chapter is a combination of asp.net,spring.net,nhibernate, the first two friends know that the first two articles are just ASP. NET MVC and spring.net,asp.net MVC and NHibernate alone. This chapter is the last of the three combinations of ASP. NET MVC + spring.net +nhibernate. Okay, here's the beginning of the chapter.
This time use is Spring.net 1.3.2,nhibernate3.2.0,asp.net MVC3. The development environment is VS2012

First, create a solution "ASH"
Create 4 projects in a solution:
"Com.Symjie.Web"
"Com.Symjie.Model"
"Com.symjie.BLL"
"Com.Symjie.DAL"
and add the mutual references between them (three layers of knowledge, no longer described here).

and add a "Config" folder to each project, which is used to store spring.net and nhibernate configuration files.

Second, starting from the model, configure the NHibernate mapping file
Here we use "Entity Developer" This software to generate nhibernate mapping files, of course, manual writing can also. Add the resulting file to the model project.

Then change the properties of the User.hbm.xml file to "embedded resources".


User.cs Code:

Using system;using system.collections;using system.componentmodel;using system.linq;using System.Text;using System.collections.generic;namespace com.symjie.model{public    partial class User {            partial void oncreated ();                Public User ()        {            oncreated ();        }        public virtual int Uid        {            get;            Set;        }        Public virtual string Uname        {            get;            Set;}}    }

User.hbm.xml File Contents:

<?xml version= "1.0" encoding= "Utf-8"? >


Third, start with the DAL, first let spring.net and NHibernate together
The reason to start with the DAL is because spring.net and nhibernate combine more complex (for friends who just touch). Since the DAL is dealing with the database, in the DAL project, we are going to introduce several of the following DLL files.
NHibernate:
NHibernnate.dll
Iesi.Collections.dll


Spring.net
Temporarily not introduced, of course, the introduction of the core DLL files can also. If the next course is used, we'll add it up.

Three files were created:
INHibernateSessionFactory.cs provides management of the ISession:

Public interface inhibernatesessionfactory{nhibernate.isessionfactory Sessionfactory {set; get;}}

Id_user.cs is an abstract interface to D_user that defines the method of implementation

public interface id_user{ilist<model.user> GetAllUsers ();    }

D_user.cs is a concrete implementation, to realize the interface above the two interfaces, fully embodies the spring.net IOC.

public class D_user:id_user,inhibernatesessionfactory{public nhibernate.isessionfactory Sessionfactory{get;set;} Public ilist<model.user> GetAllUsers () {nhibernate.isession session = this  . Sessionfactory.getcurrentsession ();            Nhibernate.iquery query = session. CreateQuery ("from User"); return query. List<model.user> ();}    }

Then is the most difficult part, is to write spring.net configuration file, let spring.net to manage NHibernate.
First, create a springnhibernate.xml file in config. This file is used to configure the management nhibernate. Also set to "Embedded Resource". The contents are as follows:

<?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--<descripti On> using Spring.net Management NHibernate </description> <!--through the context profile reference of the main application, In fact, it is to read the contents of the databasesettings in Web. config, interacting with the db:provider below--<object type= " Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.core "> <property name=" configsections " Value= "Databasesettings"/> </object> <!--database configuration, in fact, is to provide the database connection string and the corresponding database DLL file, The MySql-5.2.3 is used here, and there is no need to reference the MySql.Data.dll file in the project (maybe bring your own). Where the content of the $ symbol is a placeholder, its value is set in Web. config--<db:provider id= "Dbprovider" provider= "MySql-5.2.3" connectionstring= " Server=${db.server};D Atabase=${db.database};uid=${db.user};p Wd=${db.password} "/> <!--NHibernate configuration -<!--can specify an alias for it by name Name= "Sessionfactory" the management object used to set NHibernate session, using the Localsessi provided by spring.netOnfactoryobject to manage the nhibernate session. Because the nhibernate session is thread insecure. --<object id= "mynhibernatesessionfactory" type= "Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate32 > <!--about the configuration of database connections, use the settings in Dbprovider directly, so that you do not need to provide Hibernate with connection strings and drivers--- Lt;property name= "Dbprovider" ref= "Dbprovider"/> <!--assembly containing mapped files, HBM assembly name to be analyzed---<property name= "Mapp Ingassemblies "> <list> <value>Com.Symjie.Model</value> </list> </propert Y> <!--other Parameters--<property name= "Hibernateproperties" > <dictionary> <!--dialect--&        Gt <entry key= "dialect" value= "NHibernate.Dialect.MySQL5Dialect"/> <entry key= "use_proxy_validator" value= "FA LSE "/> <entry key=" Show_sql "value=" true "/> </dictionary> </property> <!--and SPR Ing. NET uses transactions, you must set this key--<property name= "Exposetransactionawaresessionfactory" Value= "true"/> </object></objects> 

Then in config create a "objects.xml", this file is the Spring.net object file, used to implement the IOC. There is an attribute sessionfactory in D_user. This property is associated with "mynhibernatesessionfactory", In other words, the Mynhibernatesessionfactory object defined in Springnhibernate is an instance of Sessionfactory. Then you need to inject this object into the Sessionfactory attribute of the D_user. At the same time this is objects.xml set to "Embedded Resource".
Objects.xml content is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><objects xmlns= "http://www.springframework.net" xmlns:tx= "http// Www.springframework.net/tx ">  <object id=" D_userimpl "type=" Com.Symjie.DAL.D_User, Com.Symjie.DAL "    >    <!--ref represents the referenced object, note that this mynhibernatesessionfactory is the object defined in Springnhibernate--    <property name= "Sessionfactory" ref= "mynhibernatesessionfactory"  />  </object></objects>

This completes the combination of spring.net and nhibernate, which can be used below.

Iv. completion of the spring management of the BLL layer
Before using it, we completed the spring management of the BLL layer first. Create two files in the BLL:
Ib_user.cs defining the related properties and methods of B_user

Public interface Ib_user{dal.id_user D_user {set; get;} Ilist<model.user> GetAllUsers ();}

B_user.cs implements the methods and properties of Ib_user

public class B_user:ib_user{public Dal.id_user D_user{get;set;} Public ilist<model.user> GetAllUsers () {return this. D_user.getallusers ();}}

Then create the Bll.xml file in config. This file is the Spring.net object file that is used to implement the IOC.

<objects xmlns= "Http://www.springframework.net" >    <object id= "B_userimpl" type= "Com.Symjie.BLL.B_User , Com.Symjie.BLL "    >        <!--ref represents the object being referenced--        <property name=" D_user "  ref=" D_userimpl "/>    </object></objects>

Also set the Bll.xml as "Embedded Resource". OK, so the BLL and the Dal have all been configured, so here's how to use it.

Configuring Web Projects and Spring.net,nhibernate
First, in the Web project we added the spring.net DLL file to the first.
Spring.core,spring.data.spring.aop,spring.data.nhibernate32
Then create the "controllers.xml" file in the Config folder, let the MVC controller through the spring.net to manage, simultaneously implements the IOC.
Create a homecontroller and corresponding view file. The contents are as follows:
HomeController.cs

public class Homecontroller:controller{private BLL. Ib_user B_user {get; set;} Public ActionResult Index () {viewbag.data = B_user.getallusers (); return View ();}}

Index.cshtml

@using com.symjie.model;@{    Layout = null;} <! DOCTYPE html>

This section, primarily the configuration of Web. config, is very important in some places. First look at how to configure the Web. config file.
Open the Web. config file and start configuring spring.

<?xml version= "1.0" encoding= "Utf-8"?><!--For more information about how to configure an ASP. NET application, go to http://go.microsoft.com/fwlink/? linkid=152368--><configuration> <configSections> <sectiongroup name= "Spring" > <section na    Me= "Context" type= "Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc3"/> </sectionGroup> <section name= "databasesettings" type= "System.Configuration.NameValueSectionHandler"/> </configsections ><spring> <context> <resource uri= "Assembly://com.symjie.dal/com.symjie.dal.config/springnhi Bernate.xml "/> <resource uri=" Assembly://com.symjie.dal/com.symjie.dal.config/objects.xml "/> <resour Ce uri= "assembly://com.symjie.bll/com.symjie.bll.config/bll.xml"/> <resource uri= "file://~/Config/ Controllers.xml "/> </context> </spring><!--Database related information, and related to Springnhibernate.xml. -<databaseSettings> <add key= "Db.server" value= "127.0.0.1 "/> <add key=" db.database "value=" NHibernate "/> <add key=" Db.user "value=" root "/> <add key= "Db.password" value= "Symjie"/> </databaseSettings> <appSettings> <add key= "webpages:version" value = "1.0.0.0"/> <add key= "clientvalidationenabled" value= "true"/><add key= "unobtrusivejavascriptenabled" Value= "true"/><!--need to configure the ID of the sessionfactory at the appsettings node, the same ID as the Springnhibernate object name in Sessionfactory. --<add key= "Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value= " Mynhibernatesessionfactory "/> </appSettings> <system.web><!--This is the setting in IIS6, if it is used higher than this, see the settings below. Note: If you are using vs2010 developed MVC, this entry should be set. This entry is spring. NET is used to manage the session of NHibernate, the session opens the database at the beginning of a request and closes after completion. Very important, otherwise it will be reported no Hibernate Session bound to thread, and the configuration does not allow this exception. 

Finally, don't forget to let Global.asax inherit Spring.Web.Mvc.SpringMvcApplication

Well, by this, we have completed the combination of the three, F5 preview it.

Go ASP. NET MVC spring.net NHibernate Integration

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.