Saturday, June 8, 2019

Onion architecture with MVC using repository pattern


Finally I am up with my article related to onion architecture. The main aim of this article is try to learn the onion architecture and have a sample sample code which is loosely coupled and easily maintainable. So to learn this concept efficiently, our application would consist of following:
  • An mvc application using Onion architecture.
  • Entity framework with database first approach.
  • Dependency injection using Unity container.
  • Repository pattern with a repository per entity.
So let's start with some of the basics.

What is Onion architecture ?
This architecture term was coined by Jeffrey Palermo back in 2008. Long time since then and it has become very popular these days. When you get into the details of this architecture, you might feel that you were already using from long time but may not be aware of that.
Just a quick introduction to it. Onion architecture is the way of designing your application layers in such a way that, like an onion, the innermost layer or the core component, we can say, is independent of the layer above it. As we move away from the core, the layers/components can depend on the layer towards the core but not on the layers above itself. For example, if we have 3 layers of architecture, and Layer1 is the innermost or the core layer, then Layer2 and then Layer3. So, to create an onion architecture based application would have Layer1 as the innermost layer, independent of Layer2 and Layer3. Then Layer2 comes above Layer1 and depends on only Layer1 and NOT Layer3. Finally, Layer3 is the outermost layer and can depend on both Layer1 and Layer2.
So the most important point in the onion architecture is that as we move from core to the top most layer, the dependency towards the inner layers increases. But there should not be any inter-dependency between the layers i.e. Layer2 should not depend on Layer3. So we should try to keep the core layer as much generic as possible, though not necessary always. In such a case, our architecture layers would look like the following:


 Let's try to understand by creating a new MVC application. We will create an application with tight coupling, and try to convert into Onion architecture with the system of loosely coupled components. Fire up your visual studio and add a new project of type MVC.


Next we will display some sample data on a page, from database. For this, we will create a sample database and use the entity framework database first approach. So let's add an .edmx and update it from a sample database. But, adding this edmx to the same project does not makes a good sense, as the models will be tightly coupled to the UI layer. So what we will do is that we add a new project layer of type class library, with the name SampleArchitecture.Infrastructure and add the .edmx to it. See the code below:


Next, in order to display the data from the table, we create a new class called UsersRepository.cs, in the same Infrastructure project, which will have the methods for CRUD operations related to the Users table. For our example, we will add a simple method GetAllUsers, which will get all the records from the Users table. See the code below:


Next, in order to display the data from the table, we create a new class called UsersRepository.cs, in the same Infrastructure project, which will have the methods for CRUD operations related to the Users table. For our example, we will add a simple method GetAllUsers, which will get all the records from the Users table. See the code below:


Now bind the Model in the View, run the application and see the results.



Looks good so far. But there are few issues in this code.

1. Violation of Single Responsibility Principle: The controller class is dependent on the concrete UserRepository class. The issue is that the Controller method is now responsible for multiple tasks, i.e. instantiating the repository and returning the view with the data. This violates the S of the SOLID principles, which says that each class/function should be responsible or only one task.

2. Tight coupling between the Web and the Infrastructure project:  
Our web project is directly dependent on the entities. This includes not only the Controller class but also the View (as the View will use the Model property to bind the data). So in future, for some reason, we need to remove the use of entity framework, it will not only affect the Infrastructure project but also the web application as we directly refer the entities into the Controller and View.


3. Concrete Repository class: UserRepository is concrete class in the project. As a result, where-ever, it will be used in the project, it will increase coupling between the components.


So let's start by reducing the tight coupling caused by the use of the entity framework with View and Controller. So what can we do here ? We introduce plain POCO classes, which will carry the data from the data access layer, through repository, to Controller and then finally the View. But a very important thing to be decided, where to add these POCO classes. The reason being, we are trying to use the onion architecture. We can add them to the Infrastructure project. But the point is that, these classes are just required to be container classes, carry the data and bind with the UI. So why not isolate them to another independent layer. So we add another layer called SampleArchitecture.Core,  and add its reference in the Infrastructure and the web layer. This will be also in sync with the onion architecture, where

1. Core layer will be independent of the Infrastructure and Web layers. This becomes Layer1 of our earlier discussion.

2. Infrastructure layer will be independent of the Web layer, but will be dependent on the Core layer, for the POCO classes. This becomes Layer2 of our earlier discussion.

3. Web layer will be dependent on both the Core and the Infrastructure layers, for the use of POCO classes and the repository classes. This becomes Layer3 of our discussion earlier.

So let's add a new project of type ClassLibrary and add a POCO class called UserUI. Another advantage of these classes is that we can add the validations of the model here itself.


Next, we change the repository method to use the POCO class and return the same to the Controller and bind it with the View.



Run the application and now you can see the results.



So now even if you need to remove the entity framework, just need to make changes in the Infrastructure layer. No need to change the Controller method or the View binding and hence no changes in the Core and Web layers.
Now, we will try to remove the process of creating the instance of the repository class, within the controller. For this, we will use the concept of Inversion of ControlThis means, we will invert the controllers' responsibility of initializing the repository from the Controller, to any other locationThis will be done by one of the dependency injection container named Unity. So basically this dependency injection container will be responsible for creating the required dependency and passing it to the controller. As per MSDN, Unity is:

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 order to use it, we need to add reference to the unity dll's using the nuget package manager. This is to be added in the Web project, as we need to inject the dependency on the controller methods. Let's start by adding the reference to the unity dll's.


Next, we add an interface named IUserRepository add the definition of GetAllUsers method. Implement this interface on the UserRepository class. Again the same question, where to add the interface ? And same concept to answer this question, this is a re-usable component and should be an independent component. So we add it to the SampleArchitecture.Core project. Makes sense, doesn't it ? So the code changes to:



Now the controller needs the instance of the UserRepository, which will be provided by the UnityContainer. As the name suggests, unity container is like a container which is responsible for providing the required dependency to a class. In our example, we need the UserRepository instance. So unity container will provide it, to us. But before it can do that, we need to register the required dependencies with the container. Registering the dependency is like telling the container that when i am using this interface, provide me an instance of the concrete class that implements this interface. At run time, get the required dependency from this container and inject to the required method using the Constructor, Property or Method injection process.
So for this, we add a class named UnityConainerRegistration and register the dependencies. We add this class in the main web project as this is where we need the dependencies to be resolved


Next, we initialize this container in the Global.asax file. So when the application is started, it will register all the dependencies in the container.

Next, we initialize this container in the Global.asax file. So when the application is started, it will register all the dependencies in the container.


So now run the application and there is no affect on the results. But in the application code, our the dependency follows what we aimed at i.e. the onion architecture. Our SampleArchitecture.Core is the innermost layer which is independent of everything. Then we have the SampleArchitecture.Infrastructure, which is dependent on the Core layer and independent of the web layer. Finally we have the web layer which is dependent on both the Core and the Infrastructure layer. This is what we aimed at:

So now run the application and there is no Effect on the results. But in the application code, our the dependency follows what we aimed at i.e. the onion architecture. Our SampleArchitecture.Core is the innermost layer which is independent of everything. Then we have the SampleArchitecture.Infrastructure, which is dependent on the Core layer and independent of the web layer. Finally we have the web layer which is dependent on both the Core and the Infrastructure layer. This is what we aimed at:So this is what we discussed in the starting. Wasn't that easy to learn. Hope you enjoyed reading it. Happy coding...!!!

Sunday, March 26, 2017

Dependency injection using property in C#

In my previous articles, we discussed how we can inject the dependency using constructor and method. This is the final approach we can use to inject the dependency where we will see how we can implement the dependency injection using the property injection. We will be using the same code which we used in our previous discussions.

In property injection, we simply create a property of the type of dependency required by our class. Whenever we need to call a method which needs a dependency to be used, we set the property of the class, to the required concrete implementation of the dependency. In our case, we will create a property named logger which is of type ILogger, in the TestClass. So our code changes to:

public class TestClass  
{  
    public ILogger logger  
    {  
        get;  
        set;  
    }  
  
    public void GetData()  
    {   
      try  
      {  
          logger.SaveException();  
          //Get some data    
      }  
      catch (Exception ex)  
      {  
         logger.SaveException();  
      }  
   }  
}  

Now, when we call the GetData method, we will set the concrete implementation of ILogger i.e. DBLogger or TextLogger to the logger property defined in the class. So the code will look like the following:

TestClass testClass = new TestClass();  
testClass.logger = new DBLogger();  
testClass.GetData();  

That’s it. We are done with the code. This is all we have to do to implement the property injection. Run the code and generate and exception and see the results. 

This is not a much used approach, but it is useful in situations where we need to avoid the use of constructor injection, similar to the method injection. Hope you enjoyed reading these three methods. Happy coding...!!!

Dependency injection using method injection in C#

In my previous article, we discussed how we can inject the dependency using constructor. Continuing on the same lines, we will now discuss how we can implement dependency injection using the method injection. We will be using the same code which we used in our previous discussion.

The disadvantage with the constructor injection is that whenever we create an instance of the class, a new instance of the dependency gets generated and injected. It becomes available for all the method even though it was required for a single method only, as we are passing it through the constructor. So this is just not a good coding practice. So we can avoid this scenario by using the method injection.

In method injection, we change the actual method of the class (which requires dependency), to inject the dependency into it. The method will receive this dependency through parameter. So we add a new parameter to the GetData method. This parameter will be of type ILogger. So the abstraction gets passed to the class through the method itself. So our code changes to:

public class TestClass  
{  
        ILogger logger;  
   
        public void GetData(ILogger iLogger)  
        {  
            logger = iLogger;  
            try  
            {  
                //Get some data    
            }  
            catch (Exception ex)  
            {  
                logger.SaveException();  
            }  
        }  
}  


Now, when we call the GetData method, we will pass the concrete implementation of ILogger i.e. DBLogger or TextLogger to the method as a parameter. So the code will look like the following:

TestClass testClass = new TestClass();  
testClass.GetData(new DBLogger());  

That’s it. We are done with the code. This is all we have to do to implement the method injection. Run the code and generate any exception and see that the DBLogger method get's called.

Dependency injection using constructor in C#

In my previous article we discussed about the concept of dependency injection and inversion of control. Continuing on the same lines, we will now discuss how we can implement the dependency injection using the constructor injection. We will be using the same code which we used in our previous discussion.

As the name suggests itself, in this scenario, we use the constructors of the class, to inject the dependency into it. So we add a new parameterized constructor in the class. This parameter will be of type ILogger. So the abstraction gets passed to the class through the constructor, whenever an instance of the class is created. So our code changes to:

public class TestClass  
{  
    ILogger logger;  
  
    public TestClass(ILogger iLogger)  
    {  
      logger = iLogger;  
    }  
    public void GetData()  
    {  
      try  
      {  
        //Get some data    
      }  
      catch (Exception ex)  
      {  
          logger.SaveException();  
      }  
    }  
}  


Now, when we call the GetData method, we will be creating a new instance of the class and pass the concrete implementation of ILogger i.e. DBLogger or TextLogger to the constructor. So the code will look like the following:


TestClass testClass = new TestClass(new TextLogger());  
testClass.GetData();  


That’s it. We are done with the code. Run the code and generate any exception and see the results. This is all we have to do to implement the constructor injection. In my next article, we will see how we can inject dependency using method injection. Happy coding...!!!

Dependency Injection and Inversion of control using C#

In this article, we will try to understand the concept of dependency injection and inversion control. The basic idea behind dependency injection is that:
  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.
These points here suggest that whenever we have a piece of code, where one class needs to use another class, for some functionality, the main class should not directly refer to the required class. It should always depend on the abstraction rather than its concrete implementation. Let’s see with an example what we mean over here:

public class TestClass  
{  
   ILogger logger;  
   public void GetData()  
   {  
     try  
     {  
        //Get some data    
     }  
     catch (Exception ex)  
     {   
        logger.SaveException();  
     }  
   }  
}  
    
public class Logger    
{    
   public void SaveException()    
   {    
      //Log the exception to textfile  
   }    
} 


Consider the piece of code above. Here, we have a test class, which executes the GetData function. In case any exception occurs, the catch block logs the error in a text file, using the SaveException method in the Logger class. So here we can see that the GetData method is directly dependent on the Logger class to save the exception to text file.

The above implementation seems to be fine until we have a requirement that we would like to save the exception to database, instead of the text file. In such a case, we will add another method and call that method say, SaveExceptionToDatabase. Further, if we need to save the exception in any other form, again we need to change the code in this class and then call that new method. So this will be a problem as we have to change the code whenever there is a new implementation and moreover, we may break the existing GetData method by these changes.


This is where the abstractions are useful. We implement the abstractions using the interfaces and main classes use these abstractions, which is nothing but the concept of Inversion of control, which is used to make a high level module dependent on the abstractions rather then the concrete implementations.

So in order to do this, we will change our code and add an interface named ILogger with a single method named SaveException. We also add two classes named DBLogger and TextLogger. Both these classes will implement the ILogger interface. So the code will change to:

public interface ILogger  
{  
  void SaveException();  
}  
  
public class DBLogger : ILogger  
{  
   public void SaveException()  
   {  
     //Save Exception to database  
   }  
}  
public class TextLogger : ILogger  
{  
   public void SaveException()  
   {  
      //Save Exception to text file  
   }  
}  

Next, we need to change the GetData function to use the dependency through abstraction instead of the concrete implementation. For this, we change the code to remove the Logger class instance and use the ILogger instance. So the code changes to: 

public class TestClass  
{  
  ILogger logger;  
  public void GetData()  
  {  
    try  
    {  
       //Get some data    
    }  
    catch (Exception ex)  
    {   
       logger.SaveException();  
    }  
  }  
}  

Now, the point is, we have changed the main class to use the dependency through interface, but how does the GetData receive the dependency i.e. the concrete implementation for ILogger which could be either DBLogger or TextLogger. This is where we have the concept of dependency injection. We will inject the dependency into the class. For this purpose, we can use the following three techniques.
  1. Constructor injectionInject the dependency through the constructor of the class.
  2. Method injectionInject the dependency through the method of the class, which requires dependency.
  3. Property InjectionInject the dependency through a property in the main class.
We will discuss these techniques in our next articles. For complex scenarios where we may have nested or multiple depdendencies, we have the concept of IoC containers to map the dependencies. Happy coding...!!!

Friday, January 27, 2017

C# 7 Features - out variable initialization

In my previous article, we discussed about the concept of local functions in C# 7.0. In this article, we will see another feature related to the use of out type variables. 
 
Out variables are not new in C# and provide a big advantage of how we can return multiple values from a method. However, in order to pass a out type variable as a method parameter, we have to declare it first and then pass it into the method parameter, with out keyword. Something like the following: 
  1. static void Main(string[] args)  
  2. {  
  3.   
  4.             int userId;  
  5.             string userName;  
  6.             GetDetails(out userId, out userName);  
  7.   
  8.             Console.ReadKey();  
  9. }  
  10. public static void GetDetails(out Int32 UserId, out string Username)  
  11. {  
  12.             UserId = 12;  
  13.             Username = "Test User";  
  14. }  
However, in C# 7.0, we can declare the variable at the time of passing it as a method parameter, when method is being called. This means the following code will work fine in C# 7.0. 
  1. static void Main(string[] args)  
  2. {  
  3.             GetDetails(out int userId, out string userName);  
  4.             Console.ReadKey();  
  5. }  
Also, now we can have the out variable being declared as of var type, when passed as method parameter. So following code is valid and works fine in C# 7.0, which did not worked in earlier versions of C#. 
  1. static void Main(string[] args)  
  2.         {  
  3.             GetDetails(out var userId, out var userName);  
  4.             Console.ReadKey();  
  5.         }  
Hope you enjoyed reading it. Happy coding...!!!

Wednesday, January 25, 2017

Dynamic methods in C# using CodeDom

In my previous article, we discussed how we can create a dynamic class using CodeDom namespace. Now we will discuss how we can add methods to these classes. For this we will be use the same code as in our previous discussion.
For adding method to the class, we will use CodeMemberMethod class, which provides different properties, to define methods. For our sample we will create a dynamic method which will take two input parameters, calculate their sum and return the sum. Let's with basic method signatures. So our code will look like the following: 
  1. CodeTypeReference methodReturnType = new CodeTypeReference(typeof(System.Int32)); 
  2. CodeMemberMethod myMethod = new CodeMemberMethod();  
  3.   
  4.  // Generate Method signatures.  
  5.  myMethod.Name = "MySum";  
  6.  myMethod.ReturnType = methodReturnType;  
  7.  myMethod.Attributes = MemberAttributes.Public;  
We use of the CodeTypeReference class to specify the return type of our method. To add parameters for this method, we will use the CodeParameterDeclarationExpression class. So our code will look like the following: 
  1. // Initialize for Method parameters  
  2. CodeParameterDeclarationExpression methodPrm1 = new CodeParameterDeclarationExpression(typeof(Int32), "X");  
  3. CodeParameterDeclarationExpression methodPrm2 = new CodeParameterDeclarationExpression(typeof(Int32), "Y");  
  4. myMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { methodPrm1, methodPrm2 });  
Next, to specify the method definition we use the CodeSnippetExpression class. Our method will simply the sum of our input parameters. So we will generate an expression to perform the sum of the numbers and add it to the method. So our code will change to the following: 
  1. // Generate method definition  
  2. CodeSnippetExpression codeSnippet = new CodeSnippetExpression("return X + Y");  
  3.   
  4. // Add method definition to method  
  5. myMethod.Statements.Add(codeSnippet);  
Finally we add the method to our class definition using following code: 
  1. // Add method to the class.  
  2. cls.Members.Add(myMethod);  
So our complete code will look like the following: 
  1.  CodeNamespace nameSpace = new CodeNamespace("sampleNameSpace");  
  2.   
  3.  nameSpace.Imports.Add(new CodeNamespaceImport("System"));  
  4.  nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));  
  5.  nameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));  
  6.   
  7.  CodeTypeDeclaration cls = new CodeTypeDeclaration();  
  8.  cls.Name = "SampleClass";  
  9.  cls.IsClass = true;  
  10.  cls.Attributes = MemberAttributes.Public;  
  11.  nameSpace.Types.Add(cls);  
  12.   
  13.  // Initialize for Method Return type  
  14.  CodeTypeReference methodReturnType = new CodeTypeReference(typeof(System.Int32));  
  15.  CodeMemberMethod myMethod = new CodeMemberMethod();  
  16.   
  17.  // Generate Method signatures.  
  18.  myMethod.Name = "MySum";  
  19.  myMethod.ReturnType = methodReturnType;  
  20.  myMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;  
  21.   
  22.  // Initialize for Method parameters  
  23.  CodeParameterDeclarationExpression methodPrm1 = new CodeParameterDeclarationExpression(typeof(Int32), "X");  
  24.  CodeParameterDeclarationExpression methodPrm2 = new CodeParameterDeclarationExpression(typeof(Int32), "Y");  
  25.  myMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { methodPrm1, methodPrm2 });  
  26.   
  27.  // Generate method definition  
  28.  CodeSnippetExpression codeSnippet = new  CodeSnippetExpression("return X + Y");  
  29.   
  30. // Add method definition to method  
  31.  myMethod.Statements.Add(codeSnippet);  
  32.   
  33.  // Add method to the class.  
  34.  cls.Members.Add(myMethod);  
  35.   
  36.  CodeCompileUnit compileUnit = new CodeCompileUnit();  
  37.  compileUnit.Namespaces.Add(nameSpace);  
  38.  CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();  
  39.   
  40.  CSharpCodeProvider provider = new CSharpCodeProvider();  
  41.   
  42.  using (StreamWriter sw = new StreamWriter(@"C:\TestFile.cs"false))  
  43.  {  
  44.      IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");  
  45.      provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());  
  46.      tw.Close();  
  47.  }  
Run the application and see the code getting generated: 
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated by a tool.  
  4. //     Runtime Version:4.0.30319.42000  
  5. //  
  6. //     Changes to this file may cause incorrect behavior and will be lost if  
  7. //     the code is regenerated.  
  8. // </auto-generated>  
  9. //------------------------------------------------------------------------------  
  10.   
  11. namespace sampleNameSpace {  
  12.     using System;  
  13.     using System.Linq;  
  14.     using System.Text;  
  15.       
  16.       
  17.     public class SampleClass {  
  18.           
  19.         public int MySum(int X, int Y) {  
  20.             return X + Y;  
  21.         }  
  22.     }  
  23. }  
So this was about how we can generate the dynamic class and add methods to it. Hope you enjoyed reading it. Happy coding...!!!