NHibernate Best Practices with ASP.NET, 1.2nd Ed (2) 介绍

来源:互联网 发布:cult3d软件下载 编辑:程序博客网 时间:2024/05/22 05:17

Introduction(介绍)

Why Use an ORM?(为什么使用ORM)

[Author's Note: The following is an excerpt taken from a book I tinker with in my "spare" time.]
[作者注: 以下是我在“空余”时间从一本书上摘录下来]

"As we look to the horizon of a decade hence, we see no silver bullet. There is no single development, in either technology or management technique, which by itself promises even one order-of-magnitude improvement within a decade in productivity, in reliability, in simplicity." 
在往后的10年,我们认为没有银弹.无论在技术还是在管理技巧上都并不存在单一发展,在过去的每次生产力提升过程中,都可靠并简单地证明了这一点

These prophetic words were put forth by Frederick Brooks' in his now legendary paper, No Silver Bullet, in 1986. Heeding Brooks' words to a tee, it wasn't until more than a decade later, in 1997, that the software world was presented with a hint of an upcoming silver bullet in the form of NeXT's Enterprise Object Framework...one of the first object-relational mappers (ORM). Although not regularly conspicuously stated – often to avoid being seen as a heretic of software dogma – it is commonly accepted by many that ORM technologies, when used correctly, are, in fact, a silver bullet for software development. With the maturation of NHibernate, the ORM silver bullet has been formally introduced to the world of .NET. 
1986No Silver Bullet这句圣言现在被Frederick Brooks'放入他的著作中,Brook’s的说一直都是对的,直到大概10年后,即1997,在软件世界中喻为银弹的NeXT's Enterprise Object Framework,世界第一个对象-关系影射(ORM)框架发布了.虽然不成熟并经常被认为是触犯了软件教条的异教徒,但是仍被很多人普遍接受的ORM技术。事实上,当它被正确使用,它就是软件开发的银弹.随着NHibernate的成熟,ORM的中的银弹已经正式地被介绍给.net世界

The most common dissenters of ORM technologies, in general, are developers using Microsoft technologies. (As I've placed myself squarely into this realm for the past decade or so, I feel quite comfortable bringing us up first!) There seems to be an unwritten rule that "if it wasn't invented by Microsoft, then wait until Microsoft puts out the right way to do it." Stepping up to the plate, Microsoft intends to do just that with "LINQ to Entities" in the upcoming C# 3.0. (Yes, officially discard the use of "ObjectSpaces" and "DLINQ.") Developers may continue to wait for this technology or, alternatively, start realizing the benefits of ORM immediately. To be fair, the not-invented-by-Microsoft toolset for .NET developers used to be sparse but has been steadily growing since the advent of .NET. Circa 2004, the "not created by the mothership" toolset of open source tools finally began to reach a respectable level of maturity and should be seriously considered for any .NET endeavor. (And since, statistically, the majority of software projects fail, it sounds like the consideration of an expanded toolset is certainly warranted.) The impending introduction of LINQ certainly brings great benefits to flexible querying. Fortunately, LINQ is not exclusive to Microsoft data-access layers and LINQ for NHibernate is already well underway by Ayende Rahien.
大部分不同意ORM技术的人,总体上都是使用微软技术的.(在过去大约10年中,当我注视着这个领域,我感觉非常舒服地把我们带到第一(这句不知道应该怎样翻译比较准确))这里有个看似不成文的规定“如果不是由微软发明的,那么我们一直等待,直到微软把它做“对”为止).继续话题,微软计划在将来C#3.0中的”LINQ To Entities”使用ORM(是的,官方已经正式抛弃了”ObjectSpaces””DLINQ”)开发人员可以一直等待,或者,选择马上开始获得ORM所带来的好处.老实说(或者翻译“说几句公道话”),这个非微软发明的.net工具在.net开发人员中很少被使用,单自从它来到.net中后已经稳定的成长起来.大约2005,这个“非原厂生产”的开源工具已经成熟到令人尊敬,并且被很多.net用户认证考虑.(根据统计学上来说,大部分的软件项目都是失败,这听起来扩展工具是值得的)即将推出的LINQ的可伸缩查询语句肯定会带来巨大的好处,幸运地,LINQ并不是单单用在微软的数据访问层 并且Ayende Rahien已经进行着LINQ for NHibernate

Other dissenters of these technologies suggest that ORMs kill application performance and only provide a significant improvement to productivity in the initial stages of development. Furthermore, the argument continues, is that the use of an ORM becomes a serious detriment to project success only later in the project, when issues of performance and maintainability begin to have a more noticeable effect. Three obvious retorts come to mind in response to these protests.
其次 这个技术的反对者认为ORM技术扼杀程序性能的同时,只是在开发初期改善开发速度。此外,这个论点继续,认为当发布项目后的可维护性和性能变得很重要的时候,ORM会是项目后期的成功一个严重障碍。三个明显反驳浮现脑海,在回应这些论点

First and foremost, in support of ORMs, using a framework such as NHibernate increases your performance as a developer. If you can spend 90% less time (yes, I said "90% less time") on developing data access code, then quality time can be spent improving the domain model and tuning performance – assuming it becomes necessary. Furthermore, leveraging a simple profiling tool goes a long way towards implicating the 5% of code that's causing 95% of the performance bottleneck. And in the cases in which the data access layer is the bottleneck, simple adjustments can usually be made to reap substantial improvements. Incidentally, this is no different than when not using an ORM. (Be sure to check out Peter Weissbrod's introductory article to profiling NHibernate applications.) And in the very few situations in which the ORM framework is the bottleneck and can't be adjusted for improvement, it's trivially simple to bypass the ORM altogether if the data access layer has been properly abstracted.
首先,在使用如NHibernate这些能够支持ORM的框架能够增加开发商的效率。如果能够节省至少90%开发数据访问代码的时间(是的,我说至少“90%”的时间),如果需要,那么节省了用于质量保证的时间可以用于改善领域模型和调试性能。此外,使用简单的工具可以有效地节省5%的引起95%性能问题代码。万一性能瓶颈是由于数据访问层引起,通常也只需简单的调整就收到不错的改善。顺便提及一下,这和不使用ORM是一样的。(一定查看一下Peter Weissbrod的《introductory article to profiling NHibernate applications》)而且ORM是性能瓶颈并且无法调整的情况是很少的,如果数据访问层适当地分离,把ORM完全置之不理也是很平常的做法

Secondly, NHibernate, specifically, provides an incredible amount of control over all aspects of data-loading behavior. This has positive effects on developer productivity, application scalability, and application stability. Caching is certainly available – but this is readily available in non-ORM solutions as well. Other out-of-the-box features include lazy loading, support for inheritance, declaration of immutable classes, loading of read-only properties, support for generics, stored procedures, blah blah blah. The point is that all these powerful features have been proven in real-world scenarios and, therefore, have removed many hours of developing, debugging and tweaking a custom data access layer. (And if you really feel the need to get into the code, that's just fine since NHibernate's an open source project.)
第二,NHinbernate 特别地提供大量面向数据载入行为面向方面的控制。这些一定能够改善开发人员的生产力,提高程序灵活度和稳定性。缓存是被肯定的-但最好不要用在非ORM解决方案中(注:不知道是否这样翻译)。另外的其他特性包括懒加载,支持继承,不可变类声明,加载数据到只读属性,支持泛型、存储过程等待。这些强大的特性都在在实际项目中被验证可行的,另外这些都能够在减少自定义数据访问层的改错和调试时间(如果你想需要进入代码中(调试)非常好NHibernate是个开源项目)

Finally, I would argue that those who feel that ORMs like NHibernate become maintenance headaches later in a project are working with a coding architecture that would inhibit the maintenance of any data access layer. Just because I've suggested that NHibernate is a silver bullet doesn't imply that it eliminates the need for proper application design. With the proper amount of judicious, architectural forethought, NHibernate is quite possibly the most maintainable solution for tying a .NET application to a database.
最后,我愿意说服那些认为像HibernateORM会使项目后期的维护变得头痛、并正在愿意维护其他数据分访问层架构的人。只是因为 我会认为NHibernate是个银弹但并不意味着它不需要作适当的应用设计。作为正确明智前瞻的架构,Nhibernate是十分可能为.net数据库程序提供最大的可维护性

Needless to say, NHibernate, like other ORM tools, has alleviated the maintenance of thousands of lines of code and stored procedures, thus allowing developers to focus more attention on the core of a project: its domain model and business logic. Even if you automatically generate your ADO.NET data-access layer using a tool such as CodeSmith or LLBLGen Pro, NHibernate provides the flexibility in decoupling your domain model from your relational model. Your database should be an "implementation detail" that is defined to support your domain model, not the other way around. The remainder of this article focuses on describing best practices for integrating NHibernate into ASP.NET using well established design patterns and "lessons learned from the field".
不必说,Nhibernate 或其他ORM工具,缓解了数十万行的代码和存储程序的维护,从而让开发人员更加注重对项目的核心:及时领域模型和商业逻辑。即使如果你使用诸如CodeSmith或者LLBLGenPro去自动生成ADO.net数据访问层,Nhibernate也会为你的关系模型解耦到领域模式的提供足够的灵活度。你的数据库可以实现领域模型定义的所有细节,而不是倒过来。文章的其他部分注重介绍使用已知最好的设计模式整合NhibernateAsp.net以及“教训从外界学习”

Goals and Overview of Article 目标与概述

This article assumes a good understanding of C# and NHibernate, knowledge of the Data Access Object / Repository pattern, and at least a basic familiarity with Generics. Note that this article does not focus on using NHibernate but, instead, on integrating NHibernate into ASP.NET applications. If you're just getting acquainted with NHibernate, I'd recommend reading these two great introductions at TheServerSide.net: Part 1 and Part 2. (Also keep an eye out for Pierre Kuate's forthcoming NHibernate in Action.) For an extensive overview of the Data Access Object pattern, which is leveraged heavily within the samples, go to J2EE's BluePrints catalog. Although I use the phrase "Data Access Object" (or "DAO") throughout, it is interchangeable with Eric Evans' "Repository" in Domain-Driven Design. I just find "DAO" more convenient to type!
文章假定读者非常了解C#Hibernate,具备了数据访问对象/设计模式的知识,并且有基本的泛型知识。文中重点并不是怎样使用NHibernate,而是怎样整合Asp.netNHibernate.如果你是刚开始了解NHibernate,我推荐阅读来自TheServerSide.net的两篇介绍: Part 1 Part 2. (也关注Pierre Kuate 即将来临的NHibernate in Action.) 想了解更多重要的数据访问对象模式例子,可以到 J2EE's BluePrints catalog查阅. 虽然我使用了短语"Data Access Object" (or "DAO") , 但是这个短语可以和Eric Evans Domain-Driven Design中的' "Repository" 互换,我只是觉得"DAO" 更加方便些!

In building solid data integration within an ASP.NET 2.0 application, we aim to achieve the following objectives:

  • Presentation and domain layers should be in relative ignorance of how they communicate with the database. You should be able to modify your means of data communication with minimal modification to these layers.
  • Business logic should be easily testable without depending on a live database.
  • NHibernate features, such as lazy-loading, should be available throughout the entire ASPX page life-cycle.
  • .NET 2.0 Generics should be leveraged to alleviate duplicated code.  
在构建数据层和Asp.net2.0程序的过程中。我们遵从以下几个目标:
  • 表现层和领域层必须忽略他们怎样和数据库数据库通信. 在这些层中应该尽量最小化与数据的通信
  •  商业逻辑应该容易被测试并且无需依赖数据库。
  • NHibernate 的特性, 如赖加载(lazy-loading,应该能够被应用在整个ASPX页面的生命周期之内
  • .NET 2.0 泛型应该能够减少重复的代码

Two sample applications have been included, demonstrating the use of NHibernate with ASP.NET while meeting the above objectives:

  • Basic NHibernate Sample: This sample demonstrates the fundamentals of using NHibernate with ASP.NET and unit tests with a simple-to-understand, but not completely reusable, architecture.
  • "Enterprise" NHibernate Sample: This sample is provided with an architecturally sound grounding using proven design patterns which should allow you to quickly reuse the framework in almost any sized ASP.NET project. This sample also serves to demonstrate NHibernate with ASP.NET and "a whole bunch of other stuff" including communicating with multiple databases, using the pattern Model-View-Presenter, setting up a simple web-service which uses NHibernate, and integrating with Castle Windsor. Although code is included for communicating with multiple databases, a detailed explanation is beyond the scope of this article and may be found at the CodeProject.com article, Using NHibernate with Multiple Databases. (Note that that article's sample application is compatible with NHibernate 1.0x; albeit, the general approach is still applicable.)
两例子程序,已演示了如何nhibernateasp.net,同时满足上述目标:
  • Basic NHibernate Sample: 一个简单的示例,展示NHibernateAsp.net和单元测试中如何使用,但不是一个完全可重用的架构.
  • "Enterprise" NHibernate Sample:  这个例子提供了一个已经被验证过的设计模式,该设计模式能够允许你快速地在几乎任何规模的Asp.Net项目中重用框架。这个示例也示范了使用了NHibernateAsp.net程序和“一大堆别的东西”,其中包括和多种而数据库通信, 使用了 Model-View-Presenter 模式, 使用NHinbernate建立简单 web-service, 和整合Castle Windsor. 虽然文章包口了与多种数据库通信,但是细节问题已经超出了文件的范围,而这些细节可以在CodeProject.com中找到文章 Using NHibernate with Multiple Databases. (:该文章的示例使用NHibernate1.0x,但仍然适用于对于一般的处理方法.)

What follows now is a description of how each of the aforementioned design objectives has been tackled in the sample applications. But before getting into the implementation details, let's skip right to the chase and get the sample up and running.
以下已经将设计目标的特性已经写好到示例程序中,但是在此竟如实施细节前,让我们是到例子运行起来先