Wednesday 19 August 2015

Call method in Circular reference in C#

We have two DLLs. One is Test1.dll and Second is Test2.dll. I have added reference of Test2.dll in Test1.dll. Now  I want to call method of Test1.dll from Test2.dll. For that I have to add reference of Test1.dll in test2.dll. but .Net doesn’t allow to add circular reference. Now it is confusion how to call method of Test1.dll. but we have way to achieve it. Follow the code snippet.
 
Create Interface in Test2.dll
   public interface ICallBack
    {
        void Log(string Query);
    }
 
Class in Test2.dll.  Pass Interface object as a parameter so You can access object of Test1.dll’s class
   public class Transactions
    {
        private ICallBack callback;
        public Transactions(ICallBack objcallback)
        {
            callback = objcallback;
        }
        public void CallLog()
        {
if (callback != null)
{
     callback.Log("Ajay Patel");
}
         }
    }
 
Call Interface method from class in Test2.dll
if (callback != null)
{
     callback.Log("Ajay Patel");
}
We have completed steps in Test2.dll. Now do some trick in Test1.dll. Inherit interface to class in which we want to call method. And pass instace of class as a parameter in Test2.dll’s class constructor.
 
public class TestClass : ICallBack
{
        public TestClass()
        {
Transactions objTran = new Transactions(this)
        }
        public void Log(string Query)
        {
            // Query = “Ajay Patel” This method will called from Test2.dll
        }
}