Introduction
In these days i started use EF code first and think about how could i take the advantage form it for my recent project. My project is base on MVC3 and there are some challenges to continue update this project. At that time i must finish my job in a very shortly deadline so fast so good i just define some data access interfaces and implemented them with EF4.
There are some things in my project troubling me:
- I have used the EF entities in my controllers anywhere that there is a connection translation error throwing infrequently.
- Modules coupling degree becoming closed.
- Manage services and contexts life cycle are difficult.
Obviously it needs to refactory my project with a new architecture designing.
Preparing
Before start my work i need to do some researching and learning. I have read a large numbers of articles about DDD, SOA,EF code first, Dependency Injection pattern, Repository pattern even watch all web casts
about MVC on ASP.NET and a week later ....
I have really found some useful resources about those topics and i sharing them below:
- ASP.NET MVC Storefront Starter Kit videos
- Repository Pattern - by Martin fowler
- Microsoft Unity 2.0
- A dependency injection library for .net
- "ASP.NET MVC 3 Service Location" - by Brad Wilson
Modeling
At first i need to create the data model classes (The POCO objects) for this demo i will create Category and Product.
namespace Demo.DAL
{
public class Category
{
[Key]
public int ID { get; set; }
public virtual string Name { get; set; }
public virtual string Title { get; set; }
public virtual ICollectionProducts { get; set; }
}
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category {get;set;}
public string Name { get; set; }
public string Title { get; set; }
public string Description{get;set;}
public decimal Price { get; set; }
}
public class DB : DbContext
{
public DB() : base("DemoDB") { }
public DbSetCategories { get; set; }
public DbSetProducts { get; set; }
}
}
Repository Pattern with EF Code first
When i finish my learning on EF code first and Repository i couldn't found any solutions for implement Repository pattern with EF code first. EF4.1 is so powerful for building the DAL that it allows us using POCO
objects to define our database and BO(business objects.) instead of inherit from Entity that could be give me a big hand. I could very easy to define the repository interface like below:
public interface IRepository: IDisposable where T : class
{
///
/// Gets all objects from database
///
IQueryableAll();
///
/// Gets objects from database by filter.
///
/// Specified a filter
IQueryableFilter(Expression bool>> predicate);
///
/// Gets objects from database with filting and paging.
///
///
/// Specified a filter
/// Returns the total records count of the filter.
/// Specified the page index.
/// Specified the page size
IQueryableFilter (Expression bool>> filter , out int total, int index = 0, int size = 50);
///
/// Gets the object(s) is exists in database by specified filter.
///
/// Specified the filter expression
bool Contains(Expressionbool>> predicate);
///
/// Find object by keys.
///
/// Specified the search keys.
T Find(params object[] keys);
///
/// Find object by specified expression.
///
///
T Find(Expressionbool>> predicate);
///
/// Create a new object to database.
///
/// Specified a new object to create.
T Create(T t);
///
/// Delete the object from database.
///
/// Specified a existing object to delete.
void Delete(T t);
///
/// Delete objects from database by specified filter expression.
///
///
int Delete(Expressionbool>> predicate);
///
/// Update object changes and save to database.
///
/// Specified the object to save.
int Update(T t);
///
/// Get the total objects count.
///
int Count { get; }
}
Now create a general repository for EF code first that implement the IRepository:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data;
namespace Demo.DAL
{
public class Repository: IRepository
where TObject : class
{
protected DB Context;
protected DB Context = null;
private bool shareContext = false;
public Repository()
{
Context = new DB();
}
public Repository(DB context)
{
Context = context;
shareContext = true;
}
protected DbSetDbSet
{
get
{
return Context.Set();
}
}
public void Dispose()
{
if (shareContext && (Context != null))
Context.Dispose();
}
public virtual IQueryableAll()
{
return DbSet.AsQueryable();
}
public virtual IQueryableFilter(Expression bool>> predicate)
{
return DbSet.Where(predicate).AsQueryable();
}
public virtual IQueryableFilter(Expression bool>> filter, out int total, int index = 0, int size = 50)
{
int skipCount = index * size;
var _resetSet = filter != null ? DbSet.Where(filter).AsQueryable() : DbSet.AsQueryable();
_resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);
total = _resetSet.Count();
return _resetSet.AsQueryable();
}
public bool Contains(Expressionbool>> predicate)
{
return DbSet.Count(predicate) > 0;
}
public virtual TObject Find(params object[] keys)
{
return DbSet.Find(keys);
}
public virtual TObject Find(Expressionbool>> predicate)
{
return DbSet.FirstOrDefault(predicate);
}
public virtual TObject Create(TObject TObject)
{
var newEntry = DbSet.Add(TObject);
if (!shareContext)
Context.SaveChanges();
return newEntry;
}
public virtual int Count
{
get
{
return DbSet.Count();
}
}
public virtual int Delete(TObject TObject)
{
DbSet.Remove(TObject);
if (!shareContext)
return Context.SaveChanges();
return 0;
}
public virtual int Update(TObject TObject)
{
var entry = Context.Entry(TObject);
DbSet.Attach(TObject);
entry.State = EntityState.Modified;
if (!shareContext)
return Context.SaveChanges();
return 0;
}
public virtual int Delete(Expressionbool>> predicate)
{
var objects = Filter(predicate);
foreach (var obj in objects)
DbSet.Remove(obj);
if (!shareContext)
return Context.SaveChanges();
return 0;
}
}
}
The Repository has two running mode:exclusive mode and shared mode.
- Exclusive mode:The data context is generated by Repository, the data objects only use in the Repository's data context. (Update,Delete)
- Shared mode:In many scenarios we maybe use over 1 repositories at the same time. If repositories has their own data context, it may be cause the data duplicate issue.So we need to pass the shared data context
to repositories in transaction on construction.
To make this example more close to reality project, i have defined two repository interfaces for Category and Product.
public interface ICategoryRepository:IRepository
{
string GetUrl();
}
public interface IProductRepository : IRepository
{
string ResolvePicture();
}
public class CategoryRepository : Repository, ICategoryRepository
{
public CategoryRepository(DB context) : base(context) { }
public string GetUrl()
{
return "";
}
}
public class ProductRepostiroy : Repository, IProductRepository
{
public ProductRepostiroy(DB context) : base(context) { }
public string ResolvePicture()
{
return "";
}
}
In order to share data context i use the UnitOfWork design pattern, to maintain the data context and interoperability repository life time.
UnitOfWork pattern
According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."
We could implement the UnitOfWork pattern in two ways,
- Implement a GeneralRepository class and embed in UnitOfWork. Then define the wapper methods and expose them to invoke the GeneralRepository. But i don't think it's the best way, because the
UnitOfWork will become very common and i couldn't use any subclass of Repository.
- Inject the IRepository descendant interfaces into UnitOfWork.
public interface IUnitOfWork:IDisposable
{
int SaveChanges();
}
public interface IDALContext : IUnitOfWork
{
ICategoryRepository Categories { get; }
IProductRepository Products { get; }
}
IUnitOfWork interface is very simple , it only use to save changes ,the IDALContext use to define the IRepository descendant interfaces , construct and maintain the data context and Repostiory classes.
public class DALContext : IDALContext
{
private DB dbContext;
private ICategoryRepository categories;
private IProductRepository products;
public DALContext()
{
dbContext = new DB();
}
public ICategoryRepository Categories
{
get
{
if (categories == null)
categories = new CategoryRepository(dbContext);
return categories;
}
}
public IProductRepository Products
{
get
{
if (products == null)
products = new ProductRepostiroy(dbContext);
return products;
}
}
public int SaveChanges()
{
throw new NotImplementedException();
}
public void Dispose()
{
if (categories != null)
categories.Dispose();
if (products != null)
products.Dispose();
if (dbContext != null)
dbContext.Dispose();
GC.SuppressFinalize(this);
}
}
Service Layer
The DAL has been done! Constantly we need to create the SL (Service Layer). Now i create new service interface to get categories,products or create new product.
Through the service layer, used to encapsulate data level of implementation details, call the interface should be designed to be simple as possible. Service layer is usually called by the Controller in the MVC, Controller
only needs to use the service interface, and the DI is responsible for construction, such a Controller and data layer of coupling is greatly reduced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using Demo.DAL;
namespace Demo.Services
{
public interface ICatalogService
{
ListGetCategories();
ListGetProducts();
Product CreateProduct(string categoryName, string productName, int price);
}
public class CatalogService : ICatalogService, IDisposable
{
private IDALContext context;
public CatalogService(IDALContext dal)
{
context = dal;
}
public ListGetCategories()
{
return context.Categories.All().ToList();
}
public ListGetProducts()
{
return context.Products.All().ToList();
}
public Product CreateProduct(string categoryName, string productName, int price)
{
var category = new Category() { Name = categoryName };
var product = new Product() { Name=productName,Price=price,Category=category };
context.Products.Create(product);
context.SaveChanges();
return product;
}
public void Dispose()
{
if (context != null)
context.Dispose();
}
}
}
Controller
Pass the ICatalogService instance to controller by used construction injection.
public class HomeController : Controller
{
private ICatalogService service;
public HomeController(ICatalogService srv)
{
service = srv;
}
public ActionResult Index()
{
ViewData.Model = service.GetCategories();
return View();
}
}
OK, that is what i want. Finally we need to construre and "Inject" instances to this object model.
Dependency Injection in MVC3
In Mvc3 we could use the DependencyResolver.SetResolver(IDependencyResolver resolver) to register a Dependency Injection Container and use IDependencyResolver.GetService() method to locate our registered
service instance that is a very amazing feature in this version. For more about DI in MVC3 you could read the "ASP.NET MVC 3 Service Location" below.
I have read many developers like to create a new ControllerFactory to inject the controller instance. Actualy that is not nessery! Because the MVC3 will call DependencyResolver.GetService to construe the Controller,
so i only need to do one thing: Implement the IDependencyResolver.
Unity
We could found many popular DI framework in google such as Castle Windsor, Structuremap,ObjectBuilder, Managed Extensibility Framework (MEF) and Microsoft Unity, I'd like to use Microsoft Unity 2.0 because
the MVC DI features in comes from it that means we could very easy to implement DI in our Mvc applications.
References from MSDN:
Unity is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection. You can use Unity in a variety of different ways to help
decouple the components of your applications, to maximize coherence in components, and to simplify design, implementation, testing, and administration of these applications.
Unity is a general-purpose container for use in any type of Microsoft® .NET Framework-based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to
register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it
resolves.
In addition,
Unity is extensible. You can write container extensions that change the behavior of the container, or add new capabilities. For example, the interception feature provided by Unity, which you can use to add policies to
objects, is implemented as a container extension.
Implement IDependencyResolver
The next step is create a DependencyResolver for MVC :
namespace Demo.Web
{
public class UnityDependencyResolver : IDependencyResolver
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
}
Open the Global.asax and register types and set DependencyReslover in Application_Start
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
container.RegisterType(new PerThreadLifetimeManager())
.RegisterType();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
That's all enjoy!
-
-
Reads(13962)
-
Permalink