Overview
Delegates in Microsoft Dynamics D365 are the methods for accessing elements in higher model from a lower model & solving dependencies among models.Delegates serves as a contract between delegate instance & delegate handler.
For example
I have a scenario.I have 2 models i.e. Model A & Model B.In Model B i passed the reference of model A but vice-versa is not possible.It means i can call objects of model A in model B.But i cannot call objects of Model B in Model A.Here we can use delegates for accessing Model B values in Model A.
Sample Code & Explanation
- Create a Model A & create a delegate.Delegate method should be empty and void type.[code language = “cpp”]
public class MyClassInModelA
{
delegate void myDelegate(EventHandlerResult _result)
{
}
}
[/code] - Create a Model B & passed the reference of Model B using “Update Model Parameters”.It means i can call objects of model A.
- Create a class in Model B & write a delegate handler.[code language = “cpp”]
class MyClassInModelB
{
[SubscribesTo(classStr(MyClassInModelA), delegateStr(MyClassInModelA, myDelegate))]
public static void myDelegateHandler(EventHandlerResult _result)
{
str ret = “Hi!This is Model B Values”;
_result.result(ret);
}
}
[/code] - Call the subscription of delegate in Model A & access the values of Model B in Model A.In this way, i am calling Values of Model B in Model A without passing the reference of Model B in Model A.[code language = “cpp”]
public class MyClassInModelA
{delegate void myDelegate(EventHandlerResult _result)
{
}
public static client server void main(Args args)
{
MyClassInModelA myClassInModelA = new MyClassInModelA();
MyClassInModelA.myMethod();
}
public void myMethod()
{
EventHandlerResult result = new EventHandlerResult();
this.myDelegate(result);
str common = result.result();
info(common);
}
}
[/code]