前言
n层的应用软件系统,由于其众多的优点,已经成为典型的软件系统架构,也已经为广大开发人员所熟知。在一个典型的三层应用软件系统中,应用系统通常被划分成以下三个层次:数据库层、应用服务层和用户界面层。如下图所示:
其中,应用服务层集中了系统的业务逻辑的处理,因此,可以说是应用软件系统中的核心部分。软件系统的健壮性、灵活性、可重用性、可升级性和可维护性,在很大程度上取决于应用服务层的设计。因此,如何构建一个良好架构的应用服务层,是应用软件开发者需要着重解决的问题。
为了使应用服务层的设计达到最好的效果,我们通常还需要对应用服务层作进一步的职能分析和层次细分。细分的结果,是能够使我们更加容易构建应用服务层的内容。
对于应用服务层来说,我们通常需要处理以下几个方面的内容:
ø 数据的表示方式
ø 数据的存取方式
ø 业务逻辑的组织方式
ø 业务服务的提供方式
ø 层的部署和层间交互
关于这些方面的讨论,可以参见拙文《面向对象的应用服务层设计》,或者在这里也能够看到同样的文章。
下面,将就这些部分在websharp中使用进行一些比较详细的说明。
数据实体的表示
websharp在数据的表现上,能够采用两种方式。
第一种方式,充分利用了.net framework类库中dataset的功能,设计了一个entitydata类。这个类继承了dataset,并增加了一些属性和方法。同数据库的映射关系,采用xml配置文件的方式。xml配置文件可以通过我们提供的工具来生成。
在实际的应用中,要获取一个product实体对象,可以通过如下方式取得:
entitydata product=entityprotypemanager. getemptyentity(“product”);
然后,可以通过如下方式来访问这个对象的属性:
string productid=customer[“productid”]
可以看到,这种方式同纯粹的面向对象的方式有点不同。在这种方式下,数据的表现形式只有一个,那就是entitydata。其好处是明显的,不用为每个实体都单独编写一个类,能够大大减少代码的编写量。其缺点也很明显,那就是不能利用编译器类型检测的功能,如果在调用对象的属性的时候,写错了属性的名称,就可能出错,但是,这个问题可以通过工具来解决。这种方式,比较符合原来使用ado编程人员的习惯。
第二种方式,我们可以编写一个product类,然后,按照标准的oo的方法来使用这个类。只不过,在编写product类的时候,必须实现persistencecapable接口,并且,同时可以使用到entitydata类的强大功能。
persistencecapable类的定义见 附1:websharp主要接口定义——persistencecapable
一个按照这个标准实现的product类的示例如下:
public class product : persistencecapable
{
private entitydata product;
public product() : this(true)
{}
public product(bool autoinit)
{
product=entityprototypemanager.getemptyentity("product");
if(autoinit)
product.newrecord();
}
public string productid
{
get{return product.getstring("productid");}
set{product["productid"]=value;}
}
public string name
{
get{return product.getstring("name");}
set{product["name"]=value;}
}
public string unitname
{
get{return product.getstring("unitname");}
set{product["unitname"]=value;}
}
public string description
{
get{return product.getstring("description");}
set{product["description"]=value;}
}
public decimal price
{
get{return product.getdecimal("price");}
set{product["price"]=value;}
}
public decimal currentcount
{
get{return product.getdecimal("currentcount");}
set{product["currentcount"]=value;}
}
public int objectcount
{
get
{
return product.entitycount;
}
}
public entitydata entitydata
{
get
{
return product;
}
set
{
product=value;
}
}
public bool next()
{
return product.next();
}
public void first()
{
product.first();
}
public void addnew()
{
product.newrecord();
}
}
可以看出,采用这种方式,product类既可以代表一个单个的product对象,也可以包含一个product对象集合,并且可以通过next和first方法来遍历。
如果要表示一对多的对象结构,我们可以采用如下的方式(表明了一个入库单的结构,这个入库单包含了入库单头和相关明细):
public class form : persistencecapable
{
private entitydata form;
private formdetail formdetail;
#region 构造函数
public form() : this(true)
{}
public form(bool autoinit)
{
form=entityprototypemanager.getemptyentity("form");
if(autoinit)
form.newrecord("form");
}
public form(entitydata entity)
{
form=entity;
}
#endregion
#region 属性
public string formid
{
get{return form["formid","form"].tostring();}
set{form["formid","form"]=value;}
}
public datetime formtime
{
get{return form.getdatetime("formtime","form");}
set{form["formtime","form"]=value;}
}
public formdetail formdetail
{
get
{
if(formdetail==null)
{
formdetail=new formdetail(form);
}
return formdetail;
}
}
#endregion
#region persistencecapable 成员
public int objectcount
{
get
{
return form.entitycount;
}
}
public entitydata entitydata
{
get
{
return form;
}
set
{
form=value;
}
}
public bool next()
{
return form.next("form");
}
public void first()
{
form.first("form");
}
public void addnew()
{
form.newrecord("form");
}
#endregion
}
public class formdetail : persistencecapable
{
private entitydata form;
#region 构造函数
public formdetail() : this(true)
{}
public formdetail(bool autoinit)
{
form=entityprototypemanager.getemptyentity("form");
if(autoinit)
form.newrecord("formdetail");
}
public formdetail(entitydata entity)
{
form=entity;
}
#endregion
#region 属性
public string formdetailid
{
get{return form["formdetailid","formdetail"].tostring();}
set{form["formdetailid","formdetail"]=value;}
}
public string formid
{
get{return form["formid","formdetail"].tostring();}
set{form["formid","formdetail"]=value;}
}
public string productid
{
get{return form["productid","formdetail"].tostring();}
set{form["productid","formdetail"]=value;}
}
public decimal incount
{
get{return form.getdecimal("incount","formdetail");}
set{form["incount","formdetail"]=value;}
}
#endregion
#region persistencecapable 成员
public int objectcount
{
get
{
return form.tables["formdetail"].rows.count;
}
}
public entitydata entitydata
{
get
{
return form;
}
set
{
form=value;
}
}
public bool next()
{
return form.next("formdetail");
}
public void first()
{
form.first("formdetail");
}
public void addnew()
{
form.newrecord("formdetail");
}
#endregion
}
数据的存取方式
数据存取的目的,是持久化保存对象。在websharp中,定义了persistencemanager接口来实现这个功能。persistencemanager的定义可以见:附1:websharp主要接口定义——persistencemanager
我们可以使用如下的方式来持久化保存一个对象:
product product=new product (true);
……//处理product
persistencemanager pm = persistencemanagerfactory.instance().
createpersistencemanager();
pm.persistnewobject(p);
pm.close();
代码非常简明和直观,没有一大堆数据库操纵的代码,也不容易发生差错。
也可以通过向persistencemanagerfactory 传递一个persistenceproperty参数来初始化一个persistencemanager,如:
persistenceproperty pp=new persistenceproperty();
pp……//设置pp的属性
persistencemanager pm = persistencemanagerfactory.instance().createpersistencemanager(pp);
关于persistenceproperty的说明,可以见后面的系统持久化配置信息一节。
事务处理
在很多时候,在处理对象保存的时候,我们需要使用事务处理,特别是在处理上上面示例中的类似于入库单的一对多结构的对象的时候。在websharp中,我们可以通过transaction 接口来完成这个功能。transaction接口的定义可以见:附1:websharp主要接口定义——transaction
下面是使用事务处理的一个例子:
product product=new product (true);
……//处理product
persistencemanager pm = persistencemanagerfactory.instance().
createpersistencemanager();
transaction trans=pm.currenttransaction;
trans.begin();
try
{
pm.persistnewobject(p);
trans.commit();
}
catch(excption e)
{
trans.rollback();
}
finally
{
pm.close();
}
对象的查询
websharp提供了对对象查询的功能,这个功能通过query接口提供。query接口的定义可以见:附1:websharp主要接口定义——query
可以通过下面的办法来使用query接口:
persistencemanager pm=persistencemanagerfactory.instance().createpersistencemanager(pp);
query q=pm.newquery("product");
q.filter="productid='p001'";
q.open();
entitydata entity=q.querydata();
datagrid1.datasource=entity;
q.close();
pm.close();
websharp也提供了直接操纵数据库的数据访问接口——dataaccess,这个接口对ado.net进行了一些封装,可以使程序员更加容易的使用ado.net的功能,并且能够屏蔽不同数据库之间的差别。这个接口的定义可以见:附1:websharp主要接口定义——dataaccess
能够通过persistencemanager的newdataaccess方法来初始化一个dataaccess对象,然后调用相应的办法来执行需要的功能。
业务逻辑的处理
有了上面的工作,我们就可以把这些对象组合起来,编写我们的业务逻辑。在面向对象的系统中,业务逻辑表现为对象之间的交互。在一些简单的系统中,没有复杂的业务逻辑,只是一些数据的维护工作,那么,有了上面两个部分的工作,我们实际上可能已经忘成了大部分的工作。
下面是一个简单的例子,表示了一张入库单入库的过程,在这个过程中,需要修改入库单上每种产品的现有库存量:
public void storeintowarehouse(form insertform)
{
formdetail detail=insertform.formdetail;
detail.first();
persistencemanager pm = persistencemanagerfactory.instance().createpersistencemanager();
transaction tm=pm.currenttransaction;
tm.begin();
try
{
if(detail.objectcount>0)
{
do
{
product product=(product)pm.findobjectbyprimarykey
(detail.productid,type.gettype
("logisticsdemo.entitydefinitions.product"));
product.currentcount+=detail.incount;
pm.updateobject(product);
}while(detail.next());
}
pm.persistnewobject(insertform);
tm.commit();
}
catch(exception e)
{
tm.rollback();
throw e;
}
finally
{
pm.close();
}
}
可以看到,在使用websharp后,对于业务逻辑的编写,可以变成一个非常自然的过程,也能够节省很多代码量。
业务服务的提供
业务外观层(business facade)的目的,是隔离系统功能的提供者和使用者,更明确地说,是隔离业务逻辑的软件的用户界面(可以参见facade设计模式)。可以使用现有的任何方法来构建构建这个层次,在我们提供的例子中,我们使用了web service。
websharp应用系统的配置
1、 缓存的配置
websharp使用了微软的cached application block来缓存数据,因此,下面的缓存信息必须在应用程序中添加。关于cached application block,可以参见微软的相关文档。
<configuration>
<configsections>
<section name="cachemanagersettings" type="microsoft.applicationblocks.cache.cacheconfigurationhandler,microsoft.applicationblocks.cache" />
<section name="websharpexpirationpolicy" type="websharp.service.websharpcofigurationhandler,websharp" />
</configsections>
<cachemanagersettings>
<!-- data protection settings
use dataprotectioninfo to set the assembly and class which implement
the dataprotection interfaces for the cache.
-->
<dataprotectioninfo assemblyname="microsoft.applicationblocks.cache"
classname="microsoft.applicationblocks.cache.dataprotection.defaultdataprotection"
validationkey="oci44oq9c3xadq3/bmhpkspfzetezlkxen/ahq8t7nvk/kmgafnssqjr00kunhrso+mplvwaingep6i14x9m+a=="
validation="sha1"/>
<!-- storage settings
use storageinfo to set the assembly and class which implement
the storage interfaces for the cache.
modes: inproc, outproc
-->
<storageinfo assemblyname="microsoft.applicationblocks.cache" classname="microsoft.applicationblocks.cache.storages.singletoncachestorage" mode="inproc" validated="true" encrypted="true" remotingurl="tcp://localhost:8282/cacheservice" />
<!--storageinfo assemblyname="microsoft.applicationblocks.cache" classname="microsoft.applicationblocks.cache.storages.sqlservercachestorage" mode="inproc" connectionstring="user id=sa;password=msljkdv1;network=dbmssocn;database=cacheab;server=msljksrv02" encrypted="true" validated="true" applicationname="sports" remotingurl="tcp://localhost:8282/cacheservice" /-->
<!--<storageinfo assemblyname="microsoft.applicationblocks.cache" classname="microsoft.applicationblocks.cache.storages.mmfcachestorage" mode="inproc" basepath="c:\mmfcache\" encrypted="true" validated="true" mmfdictionarysize="1048576" remotingurl="tcp://localhost:8282/cacheservice"/>-->
<!--
mmfdictionarysize - it is the size (in bytes) of the dictionary object (in mmfcachestorage) used to store the references of cache items.
-->
<!-- scavenging settings
use the scavengingalgorithm to set a class that will be executed when
scavenging is performed.
-->
<scavenginginfo assemblyname="microsoft.applicationblocks.cache" classname="microsoft.applicationblocks.cache.scavenging.lruscavenging" memorypollingperiod="60" utilizationforscavenging="80" maximumsize="5"/>
<!-- expiration settings
use the expirationcheckinterval to change the interval to check for
cache items expiration. the value attribute is represented in seconds.
-->
<expirationinfo interval="1" />
</cachemanagersettings>
<websharpexpirationpolicy>
<expirationpolicy expirationcheckinterval="60" assemblyname="microsoft.applicationblocks.cache" classname="microsoft.applicationblocks.cache.expirationsimplementations.slidingtime" />
</websharpexpirationpolicy>
</configuration>
2、 系统持久化配置信息
配置persistenceproperty,对于web应用系统,可以在global.asax中配置,对于windows应用程序,可以在程序初始化时设置。
下面是设置的一个例子:
persistenceproperty pp=new persistenceproperty();
pp.connectionstring="server=127.0.0.1;uid=sa;pwd=;database=logisticsdemo;";//数据库连接字符串
pp.databasetype=databasetype.mssqlserver; //数据库类型
pp.mapfilelocation=@"websharptestlib,websharptestlib.xml"; //xml定义文件的路径
pp.mapfilelocationtye=mapfilelocationtype.assembly; //xml文件路径的类型
pp.userid="sa"; //数据库用户名,必须与数据库连接字符串中的用户名一致
pp.password=""; //数据库用户密码,必须与数据库连接字符串中的用户密码一致
applicationconfiguration.defaultpersistenceproperty=pp; //设置应用程序的默认配置属性
配置信息的说明如下:
1) 数据库连接字符串、用户名和密码的设置按照常规设置
2) mapfilelocationtye指明xml映射文件的路径类型,可以有三种类型:
a) absolutepath:采用绝对路径的形式,在这种情况下,mapfilelocation设置成绝对路径的形式,如:“d:\apppath\xml”。
b) virtualpath:对于web应用程序,可以设置为虚拟路径的形式,如“/mywebapp/entitydefinitions/”。
c) assembly:xml文件作为资源文件被编译。采用这种形式,需要将xml文件的生成操作属性设置成“嵌入的资源”,这种情况下,mapfilelocation的格式为:“assemblyname,namespace”。例如,xml文件位于websharptestlib项目的xml文件夹下面,mapfilelocation可以设置为:“websharptestlib,websharptestlib.xml”
附1:websharp主要接口定义:
persistencecapable:
public interface persistencecapable
{
entitydata entitydata{get;set;}
int objectcount{get;}
void addnew();
bool next();
void first();
}
persistencemanager:
public interface persistencemanager : idisposable
{
void close();
bool isclosed{get;}
transaction currenttransaction{ get;}
bool ignorecache{get;set;}
void persistnewobject(entitydata entity);
void persistnewobject(persistencecapable pc);
void updateobject(entitydata entity);
void updateobject(persistencecapable pc);
void deleteobject(entitydata entity);
void deleteobject(persistencecapable pc);
void reload(entitydata entity);
void reload(persistencecapable pc);
void evict (object pc);
void evictall (object[] pcs);
void evictall (icollection pcs);
void evictall ();
entitydata findentitydatabyprimarykey(object id,string entitytypename);
entitydata findentitydatabyprimarykey(object id,entitydata entity);
persistencecapable findobjectbyprimarykey(object id,persistencecapable pc);
persistencecapable findobjectbyprimarykey(object id,type entitytype);
query newquery();
query newquery(string entitytypename);
query newquery(string entitytypename,string filter);
query newquery(string entitytypename,string filter,queryparametercollection paramcolletion);
dataaccess newdataaccess();
}
transaction:
public interface transaction
{
void begin();
void commit();
void rollback();
persistencemanager persistencemanager{get;}
}
query:
public interface query
{
string entitytypename{get;set;}
string filter{get;set;}
queryparametercollection parameters
{
get;
set;
}
string ordering{get;set;}
bool ignorecache{get;set;}
entitydata querydata();
persistencecapable queryobject(persistencecapable ps);
entitydata loadsubobject(entitydata entity,string subtypename);
persistencecapable queryobject(persistencecapable ps,string subtypename);
entitydata loadsubobjects(entitydata entity);
persistencemanager persistencemanager{get;}
bool querysubobjects{get;set;}
bool isclosed{get;}
void close ();
void open();
}
dataaccess:
public interface dataaccess
{
#region support property & method
databasetype databasetype{get;}
idbconnection dbconnection{get;}
persistencemanager persistencemanager{get;}
idbtransaction begintransaction();
void open();
void close();
bool isclosed{get;}
#endregion
#region executenonquery
int executenonquery(commandtype commandtype, string commandtext);
int executenonquery(string commandtext);
int executenonquery(string commandtext, queryparametercollection commandparameters);
int executenonquery(commandtype commandtype, string commandtext, queryparametercollection commandparameters);
#endregion executenonquery
#region executedataset
dataset executedataset(commandtype commandtype, string commandtext);
dataset executedataset(string commandtext);
dataset executedataset(commandtype commandtype, string commandtext, queryparametercollection commandparameters);
dataset executedataset(string commandtext, queryparametercollection commandparameters);
dataset executedataset(commandtype commandtype, string commandtext,string tablename);
dataset executedataset(string commandtext,string tablename);
dataset executedataset(commandtype commandtype, string commandtext, queryparametercollection commandparameters,string tablename);
dataset executedataset(string commandtext, queryparametercollection commandparameters,string tablename);
dataset executedataset(commandtype commandtype, string commandtext,dataset ds);
dataset executedataset(string commandtext,dataset ds);
dataset executedataset(commandtype commandtype, string commandtext, queryparametercollection commandparameters,dataset ds);
dataset executedataset(string commandtext, queryparametercollection commandparameters,dataset ds);
dataset executedataset(commandtype commandtype, string commandtext,dataset ds,string tablename);
dataset executedataset(string commandtext,dataset ds,string tablename);
dataset executedataset(commandtype commandtype, string commandtext, queryparametercollection commandparameters,dataset ds,string tablename);
dataset executedataset(string commandtext, queryparametercollection commandparameters,dataset ds,string tablename);
#endregion executedataset
#region executereader
idatareader executereader(commandtype commandtype, string commandtext);
idatareader executereader(string commandtext);
idatareader executereader(commandtype commandtype, string commandtext, queryparametercollection commandparameters);
idatareader executereader(string commandtext, queryparametercollection commandparameters);
#endregion executereader
#region executescalar
object executescalar(commandtype commandtype, string commandtext);
object executescalar(string commandtext);
object executescalar(commandtype commandtype, string commandtext, queryparametercollection commandparameters);
object executescalar(string commandtext, queryparametercollection commandparameters);
#endregion executescalar
#region executexmlreader
xmlreader executexmlreader(commandtype commandtype, string commandtext);
xmlreader executexmlreader(string commandtext);
xmlreader executexmlreader(commandtype commandtype, string commandtext, queryparametercollection commandparameters);
xmlreader executexmlreader(string commandtext, queryparametercollection commandparameters);
#endregion executexmlreader
}
附2:使用websharp中间件开发的demo程序一份。