Sunday, 25 September 2011

Enterprise Software Architecture: How To Do It Part 4

This is part 4 in a series. For earlier and later posts in this series, please see here: Enterprise Software Architecture: How To Do It. For the accompanying code, click here.

Persisting the Entities

Any meaningful Enterprise system will need some way of persisting valid entities. A new assembly has been added to the code - the data layer. The data layer has a reference to the domain so the domain cannot reference the data layer.

Click here to download the latest code from Codeplex. Please download the code marked 'Code For Part 4'. I supplied a zip file last time but this time you will need to download straight from the downloads section - I'm still learning to use Codeplex properly!

The data layer follows the Repository Pattern, also defined here. The repository behaves like a collection, from which you can retrieve entities, add entities and query for entities.

You may remember the domain contained RepositoryContracts. This is because the domain defines what the data layer needs to do, but is not concerned with the actual persistence itself. It also means the domain can access the repository, but opinion is divided on whether you should do this. For now, the rule is you should never access the data layer from the domain.

It is the responsibility of the data layer to implement these repositories and provide the functionality that will save and retrieve entities. The persistence medium can take a number of forms, such as binary files, XML documents, an object database, but most commonly it will take the form of a relational database, such as SQL Server. Because the relational model of the database is different to the object model of the domain, we will need an Object Relational Mapper (ORM) to map between the two. In this case I have used NHibernate. I won't provide you with a tutorial on NHibernate, but instead point you to NHForge, where you can download the assemblies and then follow the Getting Started Guide.

Again, following the tests, this time in Lucid.ESA.ClientDataSystem.UnitTests/Data should demonstrate how to use the repository classes. Note that the test copies a fresh instance of the database each time it runs a test, so that the database is in a known state. This can be found in the MyTestInitialize method of each test.

Another thing to note is the SessionProvider class in Lucid.ESA.ClientDataSystem.Data/Common. This ensures that one NHibernate session is created per Http Request in the case of ASP.NET, one session per call is created in the case of WCF, and in this case, one session per test for unit testing, although to ensure this it is required to set the session in MyClassInitialize, and close the session in MyTestCleanup

No comments:

Post a Comment