Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, April 7, 2011

EF4 Self Tracking Entities & Repository design pattern

Today I'm going to talk about a new sample project I was building these days just to get to know Entity Framework 4.0 better.

After reading Mark Mishaev's post here (Building N-Tier Applications with Entity Framework 4) & a few of his references I decided to explore the self tracking entities.

As I see it, Self tracking entities is one of the most basic features the previous version of EF was missing.

Self tracking entities as the name implies is the ability of our entities to contain their state, if you're familiar with datasets & their diffgram capability than you probably used the RowState property to detect which rows are new, which are updated, deleted or unchanged - that is what tracking means.

With STE (self tracking entities) you can send your entities to your client & when receiving it back, detect easily all the changes your client made and save it to your database (of course after choosing the right concurrency strategy for your application), without it - you'll find yourself comparing the returned entity with your database to decide which changes were made & setting their state one by one before you can actually save.

So STE is the ultimate solution? Not for sure....one of the big disadvantages of STE is the fact that your client must know the actual entity - meaning:
1. It will work only if you code both the server & client (it's not always the case), proxies passing the entity's datamembers won't do the tracking stuff...
2. Your client must be .net client.
3. Any changes to entity structure/logic will require client publishing (a big minus architecturally speaking).

If you're absolutely sure you can ignore these disadvantages in your specific application - you will gain a simple & great way to track changes out of the box.

Searching for the best way to implement the use of EF I encounter many discussions about a few related patterns, the two that repeatedly stood out were Repository & UnitOfWork.

To make a long reading short..

Repository will help us separating our business logic layer from knowing anything about entity framework - potentially can allow us to control our dataAccess layer behavior (cache, trace, security etc) better and change the implementation without changing the whole application, it will also allow us to replace the repository with an in-memory repository which can be a great way to unit test our application without a database.

namespace Dieg.Framework.DataAccess
{
    public interface IRepository
    { 
        T GetById(int id);
        IEnumerable GetAll();
        IEnumerable Query(Expression<Func<T, bool>> filter);
        void Add(T entity);
        void Remove(T entity);

        void ApplyChanges(T entity);
    }
}

Implementation:

namespace Dieg.Framework.DataAccess
{
    public abstract class Repository : IRepository where T : class
    {
        protected IObjectSet _objectSet;
        protected IUnitOfWork _uow;

        public Repository(IUnitOfWork uow) 
        {
            _uow = uow;
            _objectSet = _uow.CreateObjectSet();
        }

        public abstract T GetById(int id);

        public IEnumerable GetAll()
        {
            return _objectSet;
        }

        public IEnumerable Query(System.Linq.Expressions.Expression<Func<T, bool>> filter)
        {
            return _objectSet.Where(filter);
        }

        public void Add(T entity)
        {
            _objectSet.AddObject(entity);
        }

        public void Remove(T entity)
        {
            _objectSet.DeleteObject(entity);
        }

        public abstract string Name
        {
            get;
        }

        public abstract void ApplyChanges(T entity);
    }
}

Implementing a specific repository, I prefer implementing a separate repository for each entity this way we can choose a unique behavior for each entity (for example: not all entities allow all CRUD operations, maybe there are different authorization rules for some entities etc).

namespace Dieg.MusicLibrary.DataAccess
{
    public class ArtistRepository:Repository
    {
        public const string ENTITY_NAME = "Artist"; 

        public ArtistRepository(UnitOfWork uow):base(uow)
        { }

        public override Artist GetById(int id)
        {
            return _objectSet.SingleOrDefault(a => a.Id == id);
        }

        public override string Name
        {
            get { return ENTITY_NAME; }
        }


        public override void ApplyChanges(Artist entity)
        {
            _uow.ApplyChanges(Name, entity);
        }
    }
}

UnitOfWork - 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." (The Unit Of Work Pattern And Persistence Ignorance).

namespace Dieg.Framework.DataAccess
{
    public interface IUnitOfWork
    {
        IObjectSet CreateObjectSet() where T : class;

        void SaveChanges();

        void ApplyChanges(string entityName, object entity);
    }
}

ApplyChanges method will contain the STE implementation of updating our entities state, since ApplyChanges is per entity, we can control in our BL which entities should be influenced by the specific BL method and avoid saving irrelevant changes.

Notice the implementation will have to be in the dataAcess layer project & not part of the 'framework/core/lib', since we want it to use the STE specific context extensions.

namespace Dieg.MusicLibrary.DataAccess
{
    public class UnitOfWork:IUnitOfWork, IDisposable
    {
        private readonly DiegMusicLibraryContainer _context;

        public UnitOfWork()
        {
            _context = new DiegMusicLibraryContainer();
        }
        
        public void SaveChanges()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        public IObjectSet CreateObjectSet() where E : class
        {
            return _context.CreateObjectSet();
        }

        public void ApplyChanges(string entityName, object entity)
        {
            if (entity is IObjectWithChangeTracker)
            {
                _context.ApplyChanges(entityName, (IObjectWithChangeTracker)entity);
            }
            else
            {
                throw new ArgumentException("entity must implement IObjectWithChangeTracker to use applyChanges");
            }
        }
    }
}


As I mentioned earlier, when using STE the client must have a reference to the entities, so we'll have to separate the entities from the EF context & edmx code, this can easily done using T4 templates (see :How to Separate Self-Tracking Entities to Their Own Class Library (by Gil Fink)).

Let's code a simple test to see the basic concept:

static void Main(string[] args)
        {
            Artist artist;
            
            using (UnitOfWork uow = new UnitOfWork())
            {
                ArtistRepository Artists = new ArtistRepository(uow);

                foreach (var Artist in Artists.GetAll())
                {
                    Console.WriteLine(Artist.Name);
                }
                
                artist = Artists.GetById(1);

            }

            /*unitOfWork (which holds the objectContext) is disposed here
            this will happen also when sending objects through a
              WCF (or similar) service
            */

            //change something...
            artist.ChangeTracker.ChangeTrackingEnabled = true;
            artist.Name = string.Concat(artist.Name,"AAA");


            using (UnitOfWork uow2 = new UnitOfWork())
            {
                ArtistRepository Artists = new ArtistRepository(uow2);

                //calling ApplyChanges will update the state of the artist
                //using behind the scense the STE Changetracker
                //without this the save won't recognize any changes -
                // comment the following line & try it out!!
                Artists.ApplyChanges(artist);

                uow2.SaveChanges();

                Artist b = Artists.GetById(1);
                Console.WriteLine(b.Name);
            }

            Console.ReadLine();
        }

Good luck!
Diego

Monday, November 15, 2010

Dependency Injection

Introduction

Dependency Injection (DI) is a design pattern which allows us to "inject" the concrete object into a class instead of having this initialization within the class itself.
One common way to achive similar result is using "Factory Method" design pattern.
"Factory Method" is a method, responsible for creating and returning of an instance of a class.
Usually a variable is passed to the "Factory" method to signalize which specific subclass should be returned.
The major drawbacks of the "Factory Method" are:
1. The method implementation is too specific and therefore cannot be used across other applications.
2. The creation options are hardcoded into "Factory" implementation, which means that all dependencies are known at compile time and cannot be dynamically extented without re-compiling.
3. The class which calls "Factory" method should know which subclass to create (sounds like dependency itself).

Just to make it clear: I'm not saying that using factories is bad. There are many applications in which using factories is valuable and sufficient, but if you need more flexible solution, that's when DI enters the picture.

Dependency Injection

DI is implemented by using so-called containers - configurable components that host the abstraction, create the concrete instance variables and inject it into appropriate classes.
There are many DI providers available on the market, here is the partial list:


In the following example we will use the Unity 2.0 components which is part of Enterprise Library 5.0.

The Example

Lets start with creating of a simple interface IDatabase containing a single method "Save"

interface IDataBase
{
void Save();
}

Now, we'll add two classes that implement IDatabase:

class OracleDatabase : IDataBase
{
public OracleDatabase()
{
Console.WriteLine("OracleDatabase Constructor");
}

public void Save()
{
Console.WriteLine("Save with Oracle");
}
}

And

public class SqlDatabase : IDataBase
{
public SqlDatabase()
{
Console.WriteLine("SqlDatabase Constructor");
}

public void Save()
{
Console.WriteLine("Save with SQL Server");
}
}

The "Customer" class will be the main class which uses the services of IDatabase component:

class Customer
{
private IDataBase m_Database = null;
[Dependency]
public IDataBase Database
{
get { return m_Database; }
set { m_Database = value; }
}

public void Save()
{
m_Database.Save();
}
}

The "Dependency" attribute is part of the Unity application block and it's simply a gateway used by the Unity container for the concrete type injection.

The mapping between the abstract variable and the concrete type may be performed through the code or by adding a special configuration section to App.config file.

The final usage is quite simple:

IUnityContainer container = new UnityContainer();
UnityConfigurationSection configSection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
configSection.Configure(container);
Customer customer = container.Resolve();
customer.Save();
The complete example could be downloaded here

That's it,
Mark.

Monday, October 18, 2010

Propagator Design Pattern

Introduction

I've encountered this design pattern while I was looking for an existing solution to the problem of propagating an object property to the dependant objects.
Actually the "Propagator" is based on well-known "Observer" design pattern
in which an object known as the Subject holds a list of Observers and notifies them automatically of any state changes.
The difference is that "Propagator" makes it possible to construct each object to be "Subject" and "Observer" interchangeably.

The Propagator













The idea behind the pattern is to establish a network of dependent objects and when a change occurs, push it through propagators to all descendants.

Let's give a brief explanation of each actor in the diagram above:
  1. IPropagator interface contains methods for adding/removing dependent objects and processing state changes.
  2. Propagator class, implements the IPropagator interface and contains
    the "AddHandler" method used for managing a list of delegates to be invoked when a change takes place.
  3. StateChange class represents the change itself.
  4. StateChangeOptions enum allows specifying a change propagation options.
The final usage is quite simple - we just need to call "Process" method of corresponding propagator to have all objects synchronized with the recent change.

The detailed description of Propagator design pattern along with a nice code example could be found in this post by Martijn Boeker.


That's it,
Mark.





Sunday, August 9, 2009

The Open Closed Principle

Introduction

The open closed principle of object oriented design states:
"Software entities like classes, modules and functions should be open for extension but closed for modifications."
The Open Close Principle encourages software developers to design and write code in a fashion that adding new functionality would involve minimal changes to existing code.
Most changes will be handled as new methods and new classes.
Designs following this principle would result in resilient code which does not break on addition of new functionality.

The Open Close Principle Violation Example

The code below shows a resource allocator. The resource allocator currently handles timeslot and spaceslot resource allocation:



public class ResourceAllocator
{
public enum ResourceType
{
Time,
Space
}
public int Allocate(ResourceType resourceType)
{
int resourceId = default(int);
switch (resourceType)
{
case ResourceType.Time:
resourceId = FindFreeTimeSlot();
MakeTimeSlotBusy(resourceId);
break;
case ResourceType.Space:
resourceId = FindFreeSpaceSlot();
MakeSpaceSlotBusy(resourceId);
break;
default:
throw new InvalidOperationException ("Attempted to allocate invalid resource");
break;
}
return resourceId;
}
}



It is clear from the code below that it does not follow the Open Closed Principle.
The code of the resource allocator will have to be modified for every new resource type that needs to be supported.

This has several disadvantages:

  • The resource allocator code needs to be unit tested whenever a new resource type is added.
  • Adding a new resource type introduces considerable risk in the design as almost all aspects of resource allocation have to be modified.
  • Developer adding a new resource type has to understand the inner workings for the resource allocator.

Modified Code to Support Open Closed Principle

The following code presents a new design where the resource allocator is completely transparent to the actual resource types being supported.
This is accomplished by adding a new abstraction, resource pool.
The resource allocator directly interacts with the abstract class resource pool:




public enum ResourceType
{
Time,
Space
}
public class ResourceAllocator
{
Dictionary resourcePools = new Dictionary();

public void AddResourcePool(ResourceType resourceType, ResourcePool pool)
{
if (!resourcePools.ContainsKey(resourceType))
{
resourcePools.Add(resourceType, pool);
}
}
public int Allocate(ResourceType resourceType)
{
int resourceId = default(int);
if (resourcePools.ContainsKey(resourceType))
{
resourceId = resourcePools[resourceType].FindFree();
resourcePools[resourceType].MarkBusy(resourceId);
}
else
{
throw new InvalidOperationException("Attempted to allocate invalid resource");
}
}
public int Free(ResourceType resourceType, int resourceId)
{
if (resourcePools.ContainsKey(resourceType))
{
resourcePools[resourceType].Free(resourceId);
}
else
{
throw new InvalidOperationException("Attempted to free invalid resource\n");
}
}
}

public abstract class ResourcePool
{
public abstract int FindFree();
public abstract void MarkBusy(int resourceId);
public abstract int Free(int resourceId);
}

public class TimeSlotPool : ResourcePool
{
public override int FindFree()
{ /*finds free time slot */ }
public override void MarkBusy(int resourceId)
{ /*marks slot as busy */ }
public override int Free(int resourceId)
{ /*releases slot */}
}

public class SpaceSlotPool : ResourcePool
{
public override int FindFree()
{ /*finds free space slot */ }
public override void MarkBusy(int resourceId)
{ /*marks slot as busy */ }
public override int Free(int resourceId)
{ /*releases slot */}
}

This has several advantages:

  • The resource allocator code need not be unit tested whenever a new resource type is added.
  • Adding a new resource type is fairly low risk as adding a new resource type does not involve changes to the resource allocator.
  • Developer adding a new resource type does not need understand the inner workings for the resource allocator.



Thursday, August 6, 2009

The Unit Of Work Pattern

When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database.

One of the most common design patterns that helps to form the unit, which is responsible for data persistance is the Unit of Work.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

The key thing about Unit of Work is that when it comes time to commit, the Unit of Work decides what to do. It carries out the inserts, updates, and deletes in the right order.

An article in the following link, discusses various aspects of this pattern and examines the issues around persistence ignorance.

http://msdn.microsoft.com/en-us/magazine/dd882510.aspx#id0420003

Enjoy...