Wednesday, November 23, 2011

Developing Web Applications with ASP.NET MVC3 and Entity Framework 4.1

Download source code - 754.12 KB

Introduction

ASP.NET MVC and Entity Framework is a good combination for a web application that has database backend on Microsoft platform. In this article, I will provide a demo application that is developed with the ASP.NET MVC3 and Entity Framework 4.1. The demo also adopts the following design principal, pattern and best practice to make it more flexible and extensible.
  • Separation of Concerns
  • POCO
  • Code-First
  • Registry Pattern
  • Repository Pattern
  • Persistence Ignorance
  • Dependency Injection
  • Unit Testing
In order to open and run the demo application, you need to have SQL Server/SQL Server Express with Northwind sample database and Visual Studio 2010 with ASP.NET MVC3 and Entity Framework 4.1.

Demo Application Architecture

ASP.NET MVC already has very good defined layers. In my demo, I move Model layer into its own assembly to allow reusable in other applications. Also, the model is a rich model that not just contains data and behaviors, also gets more responsibility via services. The application architecture is like this:
Architecture.gif
  • Demo.Web package contains ASP.NET MVC Views and Controllers
  • Demo.Web.Tests package contains test case for Controllers
  • Demo.Models package contains domain model, business model, and data interfaces
  • Demo.Data package contains data access logic with Entity Framework
  • Demo.Base package contains utilities for the entire application

Design Principal, Pattern, and Best Practice

I will not go through every detail of my demo application. The source code shows the complete picture. I will only focus on those design principals, patterns, and best practices used in here.

Separation of Concerns

The ASP.NET MVC already follows Separation of Concern principal pretty good, it puts UI into View layer, interaction into Controller layer, and domain entities into Model layer. The only improvement I made in this demo application is to further moving Model layer into a separate assembly and has a Data layer to contain data access logics with Entity Framework.
SeperationOfConcerns.gif

POCO

I use Visual Studio 2010 Extension Manager installed ADO.NET C# POCO Entity Generator generated my original POCO domain entity Customer and Order based on Entity Data Model (edmx). The code generated is default in Data layer, I moved them from Data layer into Model layer and completely removed code generator template files. The domain entity will be enhanced and modified manually since that except there are some major table structure changes.
CustomerClass.gif
public partial class Customer
{
 #region Primitive Properties

 public virtual string CustomerID
 {
  get;
  set;
 }

 [Required]
 public virtual string CompanyName
 {
  get;
  set;
 }

 public virtual string ContactName
 {
  get;
  set;
 }

 public virtual string ContactTitle
 {
  get;
  set;
 }

 public virtual string Address
 {
  get;
  set;
 }

 public virtual string City
 {
  get;
  set;
 }

 public virtual string Region
 {
  get;
  set;
 }

 public virtual string PostalCode
 {
  get;
  set;
 }

 public virtual string Country
 {
  get;
  set;
 }

 public virtual string Phone
 {
  get;
  set;
 }

 public virtual string Fax
 {
  get;
  set;
 }

 #endregion
 #region Navigation Properties

 public virtual ICollection<Order> Orders
 {
  get
  {
   if (_orders == null)
   {
    var newCollection = new FixupCollection<Order>();
    newCollection.CollectionChanged += FixupOrders;
    _orders = newCollection;
   }
   return _orders;
  }
  set
  {
   if (!ReferenceEquals(_orders, value))
   {
    var previousValue = _orders as FixupCollection<Order>;
    if (previousValue != null)
    {
     previousValue.CollectionChanged -= 
        FixupOrders;
    }
    _orders = value;
    var newValue = value as FixupCollection<Order>;
    if (newValue != null)
    {
     newValue.CollectionChanged += FixupOrders;
    }
   }
  }
 }
 private ICollection<Order> _orders;

 #endregion
 #region Association Fixup

 private void FixupOrders(object sender, NotifyCollectionChangedEventArgs e)
 {
  if (e.NewItems != null)
  {
   foreach (Order item in e.NewItems)
   {
    item.Customer = this;
   }
  }

  if (e.OldItems != null)
  {
   foreach (Order item in e.OldItems)
   {
    if (ReferenceEquals(item.Customer, this))
    {
     item.Customer = null;
    }
   }
  }
 }

 #endregion
}

Code-First

Code-First in Entity Framework is different with Model-First and Database-First. Honestly, I follow the Code-First philosophy without use exact Code-First steps to setup project in the beginning. Instead, I created Entity Data Model from database, then use it to generate the original domain entity code and moved the code into model layer. So, the Code-First approach is just to allow me to isolate future domain entity code changes with database changes completely.

Registry Pattern

Model layer has a special public static object Registry that is a well-known object to let other objects using it find common objects and services. This is an implementation of Registry pattern in Pattern of Enterprise Application Architecture (PoEAA) book. In my demo application, Registry object allows domain entities and upper layers to locate Repository service - Context and RepositoryFactory.
RegistryClass.gif
public static class Registry
{
 public static IDependencyLocator DependencyLocator;

 public static IContext Context
 {
  get
  {
   return DependencyLocator.LocateDependency<IContext>();
  }
 }
 
 public static IRepositoryFactory RepositoryFactory
 {
  get
  {
   return DependencyLocator.LocateDependency
      <IRepositoryFactory>();
  }
 }
} 

Repository Pattern

In Hibernate application, there is a pattern called Data Access Object (DAO) pattern, the Repository Pattern is the counterpart pattern with a different name in Entity Framework. I read Repository Pattern implementation code inNerdDinner, it is not separating data access logic to its own layer good enough. In my demo, Repository Interfaces all reside in Model layer to provide data service access point, then use Dependence Injection to inject specific Data layer implementation into Model layer. The reason for this kind of implementation is to promote Model centric idea and allow switching Data layer for different implementation or Unit Test.
RepositoryInterfaces.gif
RepositoryClasses.gif

Persistence Ignorance

Define data access interfaces in Model layer and put Data layer into its own assembly encourage Persistence Ignorance here, Model layer and upper layers don’t really need to worry about how the model gets loaded, updated, or saved by the data layer. Additionally, I can switch Data layer to different ORM framework, like NHibernate, or a Mock implementation whenever it is necessary.

Dependency Injection

Dependency Injection plays a crucial part in my demo. All services module need to be late bound with Model layer with Dependency Injection. In addition, the IoC container manages the lifetime of service objects. One example is theContext object. I set lifetime type as PerThreadLifetimeManager in Unity configuration. This makes one and only one context object created in a single request and the different request has a different context object. Another thing I want to mention is ASP.NET MVC3 has its own way to provide Dependency Inject for controller via implementing DependencyResolver interface. I tried it, but eventually not adopt it because my application is Model centric application, so Registry is a better place to locate all the services instead of controller constructor. The IoC container I used in the demo is Unity. The MEF IoC container is getting more popular at the moment, but it’s more intrusive to domain entities by using attribute and not allowing configurable dependencies that make me hesitate to use it.
protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();

 RegisterGlobalFilters(GlobalFilters.Filters);
 RegisterRoutes(RouteTable.Routes);

 RegisterUnityContainer();
}

private void RegisterUnityContainer()
{
 var container = new UnityContainer();
 UnityConfigurationSection section = 
   (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
 section.Configure(container);
 Registry.DependencyLocator = new UnityDependencyLocator(container);
} 

Unit Test

I usually use Test Project to automatically integration test instead of pure unit test. The reason I do this is to allow the test be more close to user acceptance test to avoid thinking of every possible test scenario for each single class in my application. In this demo, the CustomerControllerTest will have test case Index to testCustomerController Index action. There is another project Demo.DataMock that is the mock of Data layer. I can use mock framework (e.g. MOQ) to mock Data layer in test case, but I decide to not use it because I don’t want a permanent mock for Data layer in test case, I want Data layer mock during development and build process, on the other hand, I also want my test can run against the real data layer before I check in my changes to make sure the test case can be all passed in the “production” environment. I understand running again the real database is slow, but keep in mind, with test being more close to real usage allows me to uncover more possible bugs and the running again of real database is just a one time thing for each check in or before release to QA.
Web.config in Demo.Web
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IContext" type="Demo.Models.DataInterfaces.IContext, Demo.Models" />
<alias alias="Context" type="Demo.Data.Context, Demo.Data" />
<alias alias="IRepositoryFactory" 
 type="Demo.Models.DataInterfaces.IRepositoryFactory, Demo.Models" />
<alias alias="RepositoryFactory" type="Demo.Data.RepositoryFactory, Demo.Data" />
<container>
  <register type="IContext" mapTo="Context">
 <lifetime type="PerThreadLifetimeManager" />
  </register>
  <register type="IRepositoryFactory" mapTo="RepositoryFactory">
 <constructor>
   <param name="context" />
 </constructor>        
  </register>
</container>
</unity>
App.config in Demo.Web.Tests
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IContext" type="Demo.Models.DataInterfaces.IContext, Demo.Models" />
<alias alias="Context" type="Demo.DataMock.Context, Demo.DataMock" />
<alias alias="IRepositoryFactory" 
 type="Demo.Models.DataInterfaces.IRepositoryFactory, Demo.Models" />
<alias alias="RepositoryFactory" type="Demo.DataMock.RepositoryFactory, Demo.DataMock" />
<container>
  <register type="IContext" mapTo="Context">
 <lifetime type="PerThreadLifetimeManager" />
  </register>
  <register type="IRepositoryFactory" mapTo="RepositoryFactory">
 <constructor>
   <param name="context" />
 </constructor>
  </register>
</container>
</unity>


No comments:

Post a Comment