Design Pattern

Repository and Unit of framework

10 Points to Secure Your ASP.NET MVC Applications

The Repository Pattern

A repository is nothing but a class defined for an entity, with all the operations possible on that specific entity. For example, a repository for an entity Customer, will have basic CRUD operations and any other possible operations related to it. A Repository Pattern can be implemented in Following ways:

Unit of Work in the Repository Pattern

Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on kinds. To say it in simple words, it means that for a specific user action (say registration on a website), all the transactions like insert/update/delete and so on are done in one single transaction, rather then doing multiple database transactions. This means, one unit of work here involves insert/update/delete operations, all in one single transaction.

Having Multiple Repositories

Now imagine the scenario where we have multiple tables in the database. Then we need to create multiple repositories in order to map the domain model to the data model. Now having multiple repository classes poses on problem.

The problem is regarding the ObjectContext object. If we create multiple repositories, should they contain theirObjectContext separately? We know that using multiple instances of ObjectContext object simultaneously is a problem so should we really allow each repository to contain their own instances?

To solve this problem. Why to let each Repository class instance have its own instance of the ObjectContext. Why not create the instance of ObjectContext in some central location and then pass this instance to the repository classes whenever they are being instantiated. Now this new class will be called as UnitOfWork and this class will be responsible for creating the ObjectContext instance and handing over all the repository instances to the controllers.

Implement a Generic Repository and a Unit of Work Class

Creating a repository class for each entity type could result in a lot of redundant code, and it could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail. One way to minimize redundant code is to use a generic repository, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.

Repository and Unit of framework

http://www.dofactory.com/Patterns/PatternFactory.aspx#_self1

Dependency Injection

 DI is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.

For example, suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.

Problem

You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Figure 1 illustrates this.

Ff921152.4722b85b-ac16-4e68-b46d-c70e52adcd72(en-us,PandP.10).png

Q95. What are different ways to implement Dependency Injection (DI)?

Ans. There are three different ways to implement DI as given below:

 Constructor Injection - This is the most common DI. Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when instantiating that class. Injected component can be used anywhere within the class. Should be used when the injected dependency is required for the class to function. It addresses the most common scenario where a class requires one or more dependencies. 

public interface IService

    void Serve(); 

public class Service : IService 

    public void Serve() 

    {

        Console.WriteLine("Service Called");//To Do: Some Stuff 

    }

public class Client 

    private IService _service; 

    public Client(IService service) 

    { this._service = service; } 

    public void Start() 

    { 

        Console.WriteLine("Service Started"); 

        this._service.Serve(); //To Do: Some Stuff 

    }

//Builder 

class Program 

    static void Main(string[] args) 

    { 

        Client client = new Client(new Service()); 

        client.Start(); 

        Console.ReadKey(); 

    }

}

 Property Injection – This is also called Setter injection. This is used when a class has optional dependencies, or where the implementations may need to be swapped. This is used by different logger implementations like Log4Net. It may require checking for a provided implementation throughout the class (need to check for null before using it). It does not require adding or modifying constructors. 

public interface IService 

    void Serve(); 

public class Service : IService 

    public void Serve() 

    { 

        Console.WriteLine("Service Called"); //To Do: Some Stuff 

    }

public class Client 

    private IService _service; 

    public IService Service 

    { 

        set { this._service = value; } 

    } 

    public void Start() 

    { 

        Console.WriteLine("Service Started"); 

        this._service.Serve(); //To Do: Some Stuff 

    } 

//Builder 

class Program 

    static void Main(string[] args) 

    { 

        Client client = new Client(); 

        client.Service = new Service(); 

        client.Start(); 

        Console.ReadKey(); 

    } 

}

 Method Injection – This Inject the dependency into a single method, for use by that method only. It could be useful where the whole class does not need the dependency, just the one method. 

public interface IService 

    void Serve(); 

public class Service : IService 

    public void Serve() 

    { 

        Console.WriteLine("Service Called"); //To Do: Some Stuff 

    }

}

public class Client 

    private IService _service; 

    public void Start(IService service) 

    { 

        this._service = service; 

        Console.WriteLine("Service Started"); 

        this._service.Serve(); //To Do: Some Stuff 

    } 

//Builder 

class Program 

    static void Main(string[] args) 

    { 

        Client client = new Client(); 

        client.Start(new Service()); 

        Console.ReadKey(); 

    } 

}

What are advantages of Dependency Injection (DI)?

Ans. There are following advantages of DI:

 Reduces class coupling

 Increases code reusing

 Improves code maintainability

 Improves application testing

A brief introduction to Unity Container

The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

First we are creating an instance of Unity Container

IUnityContainer unityContainer = new UnityContainer();

Then we are registering the interfaces and their concrete classes

unityContainer.RegisterType<IClassB, ClassB>();

Now asking the Container to resolve to get the actual instance of the concrete class

var classB = unityContainer.Resolve<IClassB>();

But the Unity Container can intelligently identify what dependency object should be created if you specify the attribute [Dependency] in the consuming class setter methods.

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. 

//// Factory Class //public class FactoryChoice {     static public IChoice getChoiceObj(string cChoice)      {         IChoice objChoice=null;         if (cChoice.ToLower() == "car")         {             objChoice = new clsCar();         }         else if (cChoice.ToLower() == "bike")         {             objChoice = new clsBike();         }         else         {             objChoice = new InvalidChoice();         }         return objChoice;     } }   //Business classes //Car public class clsBike:IChoice {     #region IChoice Members       public string Buy()     {         return ("You choose Bike");     }       #endregion }   //Bike public class clsCar:IChoice {       #region IChoice Members       public string Buy()     {         return ("You choose Car");     }       #endregion }

Ensure a class has only one instance and provide a global point of access to it.

using System;

 

namespace DoFactory.GangOfFour.Singleton.Structural

{

  /// <summary>

  /// MainApp startup class for Structural

  /// Singleton Design Pattern.

  /// </summary>

  class MainApp

  {

    /// <summary>

    /// Entry point into console application.

    /// </summary>

    static void Main()

    {

      // Constructor is protected -- cannot use new

      Singleton s1 = Singleton.Instance();

      Singleton s2 = Singleton.Instance();

 

      // Test for same instance

      if (s1 == s2)

      {

        Console.WriteLine("Objects are the same instance");

      }

 

      // Wait for user

      Console.ReadKey();

    }

  }

 

  /// <summary>

  /// The 'Singleton' class

  /// </summary>

  class Singleton

  {

    private static Singleton _instance;

 

    // Constructor is 'protected'

    protected Singleton()

    {

    }

 

    public static Singleton Instance()

    {

      // Uses lazy initialization.

      // Note: this is not thread safe.

      if (_instance == null)

      {

        _instance = new Singleton();

      }

 

      return _instance;

    }

  }

}

1) a singleton(is a pattern specific to OO design) can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members).

2) A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues.

3) However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

static classes should not do anything need state, it is useful for putting bunch of functions together i.e Math (or Utils in projects). So the class name just give us a clue where we can find the functions and there's nothing more.

Singleton is my favorite pattern and use it to manage something at a single point. It's more flexible than static classes and can maintain state. It can implement interfaces, inherit from other classes and allow inheritance.

My rule for choosing between static and singleton:

If there are bunch of functions should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented singleton.

QuickSort

The QuickSort works as divide and conquer. It divides the unsorted list into sublists and then sorts the individual lists.

The steps of the QuickSort are:

Quicksort.png

List<int> unsorted = new List<int> { 9, 8, 7, 6 };

The quicksort function starts its work by selecting a random value from the unsorted list, this value is called the pivotvalue. Then we remove the pivot value from the unsorted list. Now each element x in the unsorted list is compared with this pivot. We have two other lists less and greater. If any element is less than the pivot, it is placed in the less list and if it is greater than the pivot value, it is placed in the greater list. Then we call the concatfunction with three arguments in it.

public List<int> quicksort( List<int> a) { Random r = new Random(); List<int> less = new List<int>(); List<int> greater = new List<int>(); if (a.Count <= 1) return a; int pos =r.Next(a.Count);  int pivot = a[pos]; a.RemoveAt(pos); foreach (int x in a) { if (x <= pivot) { less.Add(x); } else { greater.Add(x); } } return concat(quicksort(less), pivot, quicksort(greater)); }

The concat function here performs a very important role, the quicksort algorithm uses the recursive approach throgh concat function.

Here concat function receives the three arguments, two lists and pivot value. We have defined a new list of integers here name sorted. It concats the less, pivot and greater all together in sorted list and then returns this sorted list to quicksort method. The quicksort method receives this sorted list and then returns thesorted list to the function which sends the unsorted list to quicksort method.

The listing of concat is:

 Collapse | Copy Code

public List<int> concat(List<int> less, int pivot, List<int> greater) { List<int> sorted = new List<int>(less); sorted.Add(pivot); foreach (int i in greater) {  sorted.Add(i); }  return sorted;  }

MergeSort

A Merge Sort is an example of divide and conquer paradigm. It is a comparison based sorting algorithm. It takes a list and divides the list in two lists of almost equal lengths. It then sorts the list by applying merge sort recursively, which divides the divided lists into two sublists for each and applying the merge sort to them as well.

A merge sort works as follows:

Merge_sort_algorithm_diagram.png

HeapSort

The heapSort belongs to the selection sort algorithm paradigm and it is a comparison based algorithm.

The Heapsort works as a recursive fashion. It makes the heap of the given data and then sorts that heaps.

Binarytree.png

So below I have a comparison, pointing out the key differences between the patterns and why MVVM *is* different.

MVC – Model View Controller

Let’s look at MVC first. You’ll notice a few things about the diagram:

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.