Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 5 November 2020

Why use delegate?

Delegate is one of the most wrongly interpreted word by developers in C#.  Delegate is widely used inside .net framework itself. Let’s go further and break that delegate wall that every interviewer asks.

My Experience with Delegates

In my all years of experience I have used delegate several times and noticed that after I am done with development who ever over takes that code from me is not able to grasp that particular delegate logic.

 

If used wisely it can save a lot of time and lines of code but if used in inappropriately it will confuse everyone in future.

Purpose

It helps achieving following

1.      Encapsulation / Abstraction

2.      Security

3.      Callback

4.      Re-usability

Most common definition of Delegate

“Delegate is a keyword in .net that is used as function pointer” or

“Delegate is used for callbacks only”

Well nothing is wrong in these definition but these definition does not tell you the whole picture itself, it’s more confusing

Characteristics

Delegate has few characteristic

1.      Type safe

2.      Takes method in assignment

Let’s start by an example –

First let’s create our Product model

We are going to use this model

using System;

 

namespace Models

{

    public class Products

    {

        public string ProductName { get; set; }

        public int ProductId { get; set; }

    }

}

 

Let’s create and interface

General practice to create interface

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace BusinessLayer

{

    public interface ICustomer<T>

    {

        void Process(T products);

    }

}

 

Second inherit this interface in class

using Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace BusinessLayer

{

    public class FrequentCustomer : ICustomer<Products>

    {

        public void Process(Products product)

        {

            Console.WriteLine($"Product Count : 1");

            Console.WriteLine("--Product Details--");

            Console.WriteLine($"Name : {product.ProductName} Product Id : {product.ProductId}");

        }

    }

}

 

Process is the method which will be called by an anonymous later

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ServiceCallManager

{

    public static class ServiceCaller

    {

        public static void Invoke<TService>(Action<TService> action)

        {

            Type typ = typeof(TService);

            TService instance = (TService)Activator.CreateInstance(typ);

           

            action(instance);

        }

    }

}

 

Invoke is the method which takes Action<TService> type argument, in .Net Action is delegate whose return type is void

 



See the summary, it says “encapsulates

 

Now we all know delegate takes method in assignment (Encapsulates method)

Method can be in any form let’s say anonymous methods,

What is the anonymous method

“A method without name!”

 

Now let’s look into our next class

 

using BusinessLayer;

using Models;

using ServiceCallManager;

using System;

using System.Collections.Generic;

using System.Dynamic;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

namespace CallbackExample

{

    class Program

    {

        static void Main(string[] args)

        {

            IList<Products> products = new List<Products>();

 

            Products product1 = new Products();

            product1.ProductName = "Rice";

            product1.ProductId = 1;

            products.Add(product1);

 

            product1 = new Products();

            product1.ProductName = "Dal";

            product1.ProductId = 2;

            products.Add(product1);

 

            product1 = new Products();

            product1.ProductName = "Chana";

            product1.ProductId = 3;

            products.Add(product1);

 

 

            ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

 

            Console.WriteLine();

            Console.ReadKey();

        }

    }

}

ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

Remember that invoke method accepts delegate as argument and delegate encapsulates methods, so here inside Invoke method I am passing an anonymous method which will get invoked when action() is called which executes the anonymous method and calls the Process method of FrequentCustomer class

Let’s go step by step-

1.      Breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

2.      It goes inside Invoke method of static ServiceCaller class

3.      Via reflection we are creating object of ServiceT type (You can ignore this if you don’t understand reflection)

4.      At the last line of method action is called with parameter instance i.e. object of ServiceT type

5.      After action(instance) is called breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1)); and it starts executing the x => x.Process(product1) part only

6.      You will notice that x is of type FrequentCustomer 



7.      So this part of execution calls the Process method or FrequentCustomer and also passing local parameter in it

Now the benefit of delegate here is I am able to local variable inside method i.e. product1 which may not be available in other class due to security reasons

Delegate helps me implement Encapsulatiopn, Security, Callback (Obviously), Re-usability and if used wisely Polymorphism also

 

For more blogs like this please visit http://codeinout.blogspot.com/ of follow me on https://twitter.com/ishooagarwal

Thanks

 

 

Thursday, 16 April 2020

Dependency Injection in ASP.Net classes for TDD


Dependency Injection in ASP.Net classes for TDD

In Asp.Net classes there is not built in library like Unity or Autofac.

What’s the problem with plain c# classes?

The reason for that is, in MVC or Web API Controller objects are created via IHttpControllerActivator interface which is inherited by a class. In Unity library IDependencyResolver is user which is kind of a ServiceLocator anti-pattern hence objects of controllers are created without manual intervention
This IHttpControllerActivator lies in API pipeline to instantiate controllers
Now when we develop c# classes and code becomes too big and complicated and automatically becomes tightly coupled which makes TDD harder and next to impossible as once because there is no way to inject mock/test classes instead of actual DB or dll library classes

How to solve it?

We can create a ServiceLocator anti-pattern in plain old .net classes for DI purpose. Instead of directly creating object of third party dll library we can simply register those in ServiceLocator anti-pattern and then resolve the dependency within the scope of the anti-pattern

</>
       public class ServiceLocator
       {
              // Key = interface type
              // Value = concrete type that implements the Key interface
              private static readonly Dictionary<Type, ServiceTypeContainer> types;

              // used for locking, especially when creating objects using reflection
              private static object syncObject = new object();

                           static ServiceLocator()
              {
                     types = new Dictionary<Type, ServiceTypeContainer>();
                     Register<IDependency>(typeof(Dependency));
              }

              public static T Resolve<T>()
              {

                     ServiceTypeContainer typeContainer = types[typeof(T)];
                     T returnObj;

                     if (typeContainer.Initializer == null)
                     {
                           // CreateInstance uses a static cache that is not thread-safe
                           // We could change the lock to on typeContainer if this becomes a bottleneck
                           lock (syncObject)
                           {
                                  returnObj = (T)Activator.CreateInstance(typeContainer.ServiceType);
                           }
                     }
                     else
                     {
                           returnObj = (T)typeContainer.Initializer();
                     }

                     return returnObj;
              }

              public static void Register<T>(Type objT)
              {
                     Register<T>(objT, null);
              }

              public static void Register<T>(Type objT, ServiceInitializer initializer)
              {
                     types.Add(typeof(T), new ServiceTypeContainer(objT, initializer));
              }
       }

       public class ServiceTypeContainer
       {
              public Type ServiceType
              {
                     get;
                     private set;
              }

              public ServiceInitializer Initializer
              {
                     get;
                     private set;
              }

              public ServiceTypeContainer(Type serviceType, ServiceInitializer initializer)
              {
                     ServiceType = serviceType;
                     Initializer = initializer;
              }

       }

       public delegate object ServiceInitializer();

There are two classes above one is used to register classes and another type container
Now instead of tightly coupled code you can register all the third party dll classes in anti-pattern and then use it like with the interface only
As you can see I have registered the Dependency class using IDependency type and later I will resolve it using IDependency only

Practicle

Below is a class ProductHistoryClass which has parameterized constructor that takes a custom type as an argument which is in fact a reference to a service or a dll class calling another method

public class ProductHistoryClass
    {
        private IDependency dependency;

        public ProductHistoryClass(IDependency _dependency)
        {
            dependency = _dependency;
        }

        public int FindProductHistory()
        {
            return dependency.FindProductHistory();
        }
    }

Below are our dependency Interface and class
public interface IDependency
    {
        int FindProductHistory();
    }

public class Dependency : IDependency
    {
        public Dependency()
        {

        }

        public int FindProductHistory()
        {
            return 1;
        }
    }
I have kept declaration and definition simple to understand

Now in old ways we would be creating object of Dependency class and then pass the object into constructor calling of ProductHistoryClass which makes our classes tightly coupled and difficult to modify in future
So how to make use of anti-pattern here.

Don’t worry I got it covered J

In you calling class you can do like

public static void WithParam()
        {
            ProductHistoryClass prdCls = (ProductHistoryClass)Activator.CreateInstance(classType,ServiceLocator.Resolve<IDependency>());
            int res = prdCls.FindProductHistory();
        }

Here I have used reflection to create object or ProductHistoryClass and ServiceLocator to resolve our dependency

And just by these simple lines of code we are able to inject dependency in plain old c# classes
Now I would like you guys to experiment with this.
This is it from this blog hold tight till I write next one
J
If you like the blog then please like it and leave a comment
Do not forget to subscribe.
Thank you.

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...