Blog

D365 Business Central – How to Work With Codeunit Object!

D365 Business Central – How To Work With Codeunit Object!

  • A codeunit is a container for AL code that we can use in many application objects.
  • We implement business logic in codeunits and call that particular codeunit from the object that needs to perform that specific logic or action.

Basically codeunit can be used in following way:

  • First we create a codeunit snippet by using key word ‘tcodeunit’
  • After that we will give the proper ID number and name
  • In the procedure section we assign a proper name and write our logic in this section

For example:-

codeunit 50101 “Test Functions”

{

procedure Factorial()

var

IntValue, IntValue2, Fact : Integer;

begin

IntValue := 5;

IntValue2 := IntValue;

Fact := 1;

while

IntValue >= 1

do begin

Fact := Fact * IntValue;

IntValue -= 1;

end;

Message(‘IntValue = %2, My Factorial value is %1’, Fact, IntValue2);

end;

}

  • The next step is to decide in which page we should see our desired result
  • So we will create a ‘page extension’ for that page using snipper ‘tpageext’
  • Inside the action section we give our action a name and call our code unit using a trigger

For example :-

pageextension 50101 CustomerListExt extends “Item List”

{

layout

{

// Add changes to page layout here

}

actions

{

addlast(Functions)

{

action(Factorial)

{

ApplicationArea = All;

Caption = ‘Factorial’;

trigger OnAction()

var

TestFunctionCodeunit: Codeunit “Test Functions”;

begin

// TestFunctionCodeunit.Run();

TestFunctionCodeunit.Factorial();

end;

}

}

After this, we should publish our program and check for the result

Advantages of CodeUnit :-

  • CodeUnit is the best way for creating procedures
  • We can simply call those codeunits wherever we wish in our program and this help in reusability.

For more details kindly visit our LinkedIn page:

https://www.linkedin.com/company/allgrow-technologies-pvt-ltd/mycompany/

or you can write us on  contact@allgrowtech.com


Facebook

Twitter

LinkedIn

Enterprise Codeunit Architecture in Dynamics 365 Business Central

In modern Business Central development using AL, codeunits are the primary containers for domain logic, integration handlers, and event orchestration. Selecting the proper codeunit subtype and execution context ensures zero lock contention and predictable memory usage.

Codeunit Subtypes & Execution Contexts

Codeunit Subtype Lifecycle / Scope Primary Enterprise Use Case
Normal Transient (Instantiated on call, garbage collected) Standard calculation logic, API processing, document posting logic.
SingleInstance Session Persistent (Variables retain state across calls) Session-wide caching, telemetry correlation IDs, state management.
Install Extension Deployment Only Default setup records, permission sets, initial configuration tables.
Upgrade Extension Version Upgrade Data migration between schema versions (OnUpgradePerCompany).
Test Isolated Automated Test Execution Continuous Integration (CI/CD) AL unit testing and UI validation.

Clean Event Subscriber Pattern in AL

Best practice dictates isolating event subscribers into dedicated integration codeunits to decouple custom business rules from standard base application tables:

codeunit 50120 "ALGT Sales Posting Handler"
{
    [EventSubscriber(ObjectType::Codeunit, Codeunit::"Sales-Post", 'OnAfterPostSalesDoc', '', false, false)]
    local procedure OnAfterPostSalesDocHandler(var SalesHeader: Record "Sales Header"; var GenJnlPostLine: Codeunit "Gen. Jnl.-Post Line"; SalesInvHdrNo: Code[20])
    var
        IntegrationLog: Record "ALGT Integration Log";
    begin
        if SalesInvHdrNo = '' then
            exit;

        IntegrationLog.Init();
        IntegrationLog."Document No." := SalesInvHdrNo;
        IntegrationLog."Posted DateTime" := CurrentDateTime;
        IntegrationLog."User ID" := CopyStr(UserId(), 1, MaxStrLen(IntegrationLog."User ID"));
        IntegrationLog.Insert(true);
    end;
}

Need Senior Dynamics 365 Business Central Development & Architecture?

Allgrow Technologies designs scalable AL extensions, high-throughput API integrations, and CI/CD pipelines for North American enterprises. Learn about our Full-Cycle BC Implementation Services or get a free 30-minute architecture review with our lead ERP architects.

Connect with Allgrow Technologies

100% Free · No Obligation

Need an Objective Architecture or Code Assessment?

Discuss your Dynamics 365, Business Central, or Power Platform environment in a free 30-minute session with our senior engineers.

Get a Free 30-Minute Review →