Friday, February 24, 2012

Interface Dependecy Injection : A way of loose coupling in C#

To know more about Dependency Injection please read my previous post. Dependency injection can be implement by three possible ways. One of these Interface Injection.

As we know in C# an interface object can have reference of any of the class, implementing the same interface. This is the base behind the Interface Dependency Injection.
Interface injection allows to pass the dependency into dependent object in the form of interface, implemented by dependent class.
Or in easy words, Dependency declared inside the dependent class  in the form of Interface. So any class that implements dependency interface, can be substituted into dependent class.
Lets look an example:-

IDependent interface :- This interface defines the methods that inject one or more dependency into dependent class.


Dependent Class :- The class, that implement the IDependent interface.


IDependency interface :- This interface includes all dependency members that can be called from the Dependent class. By mean of IDependency interface, we can easily inject any of the class that implements IDependency interface.

Dependency Class :- Any class that implements IDependency interface use to substitute into dependent class using Interface injection.

Lets look into simple example:-
 
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceInjectionSample {

 // Project entity class
 public class Project {
   public Project(string title, int id) {
   this.title = title;
   this.id = id;
 }

 public string Title {
   get {
    return title;
   }
   set {
    title = value;
   }
 }

 public string ID {
   get {
    return id;
   }
   set {
    id = value;
   }
 }

 private string title;

 private string id;

}

// Project Business Layer class
public class ProjectBL{

  IProjectDL _projectDL;

  public ProjectBL(IProjectDL projectDL){
    _projectDL=projectDL;
  }

  public Project GetProjectById(int id){
    return _projectDL.GetProjectById(id);
  }

  public List<Project> GetProjects(){
    return _projectDL.GetProjects();
  }
}

public interface IProjectDL{
  public Project GetProjectById(id);
  public List<Project> GetProjects();
}

// Project Data Layer to interact with database.
public class ProjectDL : IProjectDL{

  public Project GetProjectById(int id){
    Project project=null;
    // logic to access database and return the mapped data object to project entity.
    return project;
  }

  public List<Project> GetProjects(){
    List<Project> projects=null;
    // logic to access database and return the mapped data object to project entity.
    return projects;
  }

 }
} 
 
 
Here Project BL class depends on IProjectDL interface to perform any operations on data layer. Since IProjectDL object can reference to any class implementing IProjectDL like ProjectDL.
By using interface dependency injection we can insert the any interface dependency.
Lets we have another implementation of IProjectDL as below:

// Another implementation of Project data layer.
// Lets assume its to interact with other database like oracle.
public class ProjectDLForOracle : IProjectDL{

  public Project GetProjectById(int id){

    Project project;

    // logic to get project from oracle database.

    return project;

  }

  public List<Project> GetProjects(){

    List<Project> projects;

    // logic to get projects from oracle database.

    return projects;

  }

} 
 
 
So ProjectBL just depend on IProjectDL implementation.  We can pass either ProjectDL or ProjectDLForOracle without changing in ProjectBL class.
Many dependency injection container available to automate and configurable this. Enterprise library also provides the policy injection block. By means of this block we can map interface to its implementing class. Policy injection block will read this configuration and inject the corresponding class instance into dependent class.
In this way BL layer classes loosely coupled with DL. We can easily change the one data layer implementation with other one.
So at the end i want to conclude about the whole content.
If dependency in the form of interface its called "Interface Dependency".
Injecting the interface dependency reference by either mean is called "Interface Dependency Injection".
I hope this article will helpful for novice to understand the concept.

Dependency Injection : A pattern for loose coupling

What is Dependency Injection?

Dependency Injection means dynamically inserting code at run time. So that application behavior can be change without affecting/recompiling whole application.

How this Injection is helpful?

Most of the application have many component which are depending on other i.e.  One component needs other to complete their job, know as Dependencies.
The purpose of most of the application architecture is to reduce the coupling between component to make the application more configurable & more loosely coupled. So that changes in one component doesn't affect other component.

Lets look at an example:-
public class BankAccount {
  private ILogger _logger = new DBLogger();

  public void Deposit(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount deposited at {0}", DateTime.Now));
  }

  public void Withdraw(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount withdraw at {0}", DateTime.Now));
  }

}
 
DBLogger object is directly instantiated inside the BankAccount class so BankAccount should know in advance about the DBLogger implementation and to change another implementation of ILogger we need to change BankAccount class too.
Lets we have another implementation of ILogger for text file logging.

public class DBLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
     // Logic to log the message to database.
    }

  #endregion
}

public class TextFileLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
      // Logic to log the message to text file.
    }

  #endregion

}
 
public interface ILogger {
  void LogTransaction(string message);
}
 
To change DBLogger to TextFileLogger in BankAccount, we need to compile BankAccount class too.

Dependency Injection (DI) remove these kind of tight coupling between component by injecting the dependency at run time.So dependent class doesn't know about the dependency at design time, DI injects dependency object's instance at run time. Based on the configuration, DI will inject the ILogger implementation in BankAccount class.

Dependency injection can be possible by three ways:
  1. Interface Injection
  2. Setter Injection
  3. Constructor Injection
Microsoft Enterprise Library provides the DI framework for all .Net applications.I am referencing MS Enterprise Library 5.0 that can be download from here .In EntLib 5.0, Policy Injection Block is kept just for the compatibility with previous version. Dependency configuration using EntLib 5.0 can be possible either by Code or by .Net configuration file.

I will continue about the dependency injection type in my next articles.

Monday, February 6, 2012

SharePoint Workflow Association : Associate workflow to list or web programmatically

Hi,
It's very frequently required to attach/associate workflow to list or web programmatically. For a workflow a history list and task list is required.
History list is use to log activity/error occurred during workflow running span.
Task list is use to create and assign task for some approval etc. to user.
Workflow Association:- The binding of any workflow template to list or web is called workflow association.

Step. 1 Create a workflow history list.

public void CreateHistoryList(){

     using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
           web.Lists.Add("YourHistoryListTitle","ListDescription",SPListTemplateType.WorkflowHistory);
        }
     }
}

Step. 2 Create a Workflow Task list.

public void CreateTaskList(){
using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
           web.Lists.Add("YourTaskListTitle","ListDescription",SPListTemplateType.Tasks);
        }
     }
}

Step. 3 Associate workflow with web ( In case of Site Workflow)


 public void AddWorkflowAssociation(){childWeb.AllowUnsafeUpdates = true;

using(SPSite site = new SPSite("Your web url")){
using(SPWeb web = site.OpenWeb()){

//Add workflow association
SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName("YourWorkflowTemplateName", new CultureInfo(1033));
SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, "Workflow Association Name",
web.Lists["TaskListTitle"], web.Lists["HistoryList"]);

//configures workflow assocition options
association.AllowManual = true;
association.AutoStartCreate = false;
association.AutoStartChange = false;
association.AllowAsyncManualStart = false;
web.WorkflowAssociations.Add(association);
web.Update();
}
     }
}

Step. 4 Associate workflow with web ( In case of List Workflow)


public void AddWorkflowAssociation(){childWeb.AllowUnsafeUpdates = true;
using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
        //Add workflow association
        SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName("YourWorkflowTemplateName", new CultureInfo(1033));
        SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, "Workflow Association Name",
                                web.Lists["TaskListTitle"], web.Lists["HistoryList"]);
        //configures workflow assocition options
        association.AllowManual = true;
        association.AutoStartCreate = false;
        association.AutoStartChange = false;
        association.AllowAsyncManualStart = false;
        SPList list = web.Lists.TryGetList("YourListTitle");
        list.WorkflowAssociations.Add(association);
        web.Update();
         }
     }
}

Now your workflow is associated with either list or web.