15

Sometimes you need to get reference to the currently executing codeunit and pass it to procedure in a different object.


You need reference to codeunit or else you will need to pass it by parameter like this:


MyCodeunit.DoSomething(MyCodeunit, ...);

And that allows library user writing code like this which is not what library developer have intended:


MyCodeunit1.DoSomething(MyCodeunit2, ...);


Codeunit self-reference is very useful to hide BindSubscription calls.


Currently, it is possible to get reference to currently executing codeunit by using event publisher and event subscriber like this but it is tedious and error prone:


codeunit 50100 "My Codeunit"

{

  Access = Internal;


  var

    GlobalParameter: Text;


  internal procedure DoSomething(Parameter: Text)

  var

    MyOtherCodeunit1: Codeunit "My Other Codeunit 1";

    MyOtherCodeunit2: Codeunit "My Other Codeunit 2";

    MyOtherCodeunit3: Codeunit "My Other Codeunit 3";

  begin

    GlobalParameter := Parameter;


    MyOtherCodeunit1.DoSomething1(GetSelf());

    MyOtherCodeunit2.DoSomething2(GetSelf());

    MyOtherCodeunit3.DoSomething3(GetSelf());

  end;


  internal procedure DoSomethingElse()

  begin

    // ...

  end;


  local procedure GetSelf() MyCodeunit: Codeunit "My Codeunit"

  begin

    OnGetSelf(MyCodeunit);

  end;


  [InternalEvent(true)]

  local procedure OnGetSelf(var MyCodeunit: Codeunit "My Codeunit")

  begin

  end;


  [EventSubscriber(

    ObjectType::Codeunit, Codeunit::"My Codeunit", 'OnGetSelf', '', false,false)]

  local procedure OnGetSelf(

    Sender: Codeunit "LBCLIC License";

    var MyCodeunit: Codeunit "My Codeunit")

  begin

    MyCodeunit := sender;

  end;

}


My suggestion is to add CurrCodeunit global in available every codeunit. If such global is already defined, the new global should not shadow it, so the existing code would not be broken.


Thanks.


P.S. Code blocks are broken. Seriously, what is with error "We have encounter some malicious input. Please remove that and try again".

Category: Development
STATUS DETAILS
Needs Votes
Ideas Administrator

Thank you for this suggestion! Currently this is not on our roadmap. We are tracking this idea and if it gathers more votes and comments we will consider it in the future. Best regards, Business Central Team

Comments

E

For further reference:https://vjeko.com/2020/11/10/top-5-things-i-miss-in-al/#:~:text=Let%E2%80%99s%20get%20started.-,%231%3A%20this%20keyword,-A%20lot%20ofWe've used this pattern when a codeunit needs reference to itself to send as parameter, e.g. to a page/codeunit which needs access to the invoker's functions and state. The current workaround (Event+StaticAutomatic+IncludeSender=True) is hard to figure out and looks a bit "dirty".

Category: Development