หน้าที่ของ infrastructure คือการจัดเตรียมความสามารถเชิงเทคนิคให้กับส่วนอื่นๆ ของแอปพลิเคชันของคุณ แม้จะไม่อยากเข้าไปพูดถึง รายละเอียดของ Layers (4) แต่การมีแนวคิด Dependency Inversion Principle อยู่ในใจก็ยังมีประโยชน์อยู่ดี ไม่ว่า infrastructure จะอยู่ตรงไหน ในเชิงสถาปัตยกรรม มันจะทำงานได้ดีมากหาก component ต่างๆ ของมันขึ้นอยู่กับ interface จาก user interface, Application Services และ domain model ที่ต้องการความสามารถเชิงเทคนิคพิเศษ ด้วยวิธีนี้ เมื่อ Application Service ค้นหา Repository มันจะขึ้นอยู่กับ interface จาก domain model เพียงอย่างเดียว ขณะที่ใช้ implementation จากฝั่ง infrastructure ส่วน Figure 14.4 แสดง UML static structure diagram เพื่ออธิบายว่ากลไกดังกล่าวทำงานอย่างไร

Image

Figure 14.4. Application Service ขึ้นอยู่กับ interface ของ Repository จาก domain model แต่ใช้ implementation class จาก infrastructure โดย package ต่างๆ จะห่อหุ้มความรับผิดชอบในวงกว้างไว้ภายใน

การค้นหานี้อาจเป็นแบบ implicit ผ่าน Dependency Injection [Fowler, DI] หรือใช้ Service Factory ก็ได้ ส่วนสุดท้ายของบทนี้ “ Enterprise Component Containers ” จะพูดถึงทางเลือกเหล่านี้ เมื่อย้อนกลับไปดูส่วนหนึ่งของ Application Service ที่เราใช้เป็นตัวอย่าง ต่อเนื่องมา เราจะเห็นอีกครั้งว่า Service Factory ถูกใช้ค้นหา Repository อย่างไร:

package com.saasovation.identityaccess.application;

public class TenantIdentityService {
    ...
    @Override
    @Transactional(readOnly=true)
    public Tenant tenant(TenantId aTenantId) {
        Tenant tenant =
            DomainRegistry
                .tenantRepository()
                .tenantOfId(aTenantId);

        return tenant;
    }
    ...
}

Application Service นี้จะเลือกฉีด Repository เข้ามาโดยตรงก็ได้ หรือจะจัดเตรียม dependencies ขาเข้าผ่าน constructor parameters ก็ได้เช่นกัน

Implementations ของ Repository ทั้งหมดถูกเก็บไว้ใน infrastructure เพราะมันจัดการกับ storage ซึ่งไม่ใช่ ความรับผิดชอบที่โมเดลควรแบกรับ คุณจะใช้ infrastructure ในการ implement interface ที่ต้องอาศัย messaging เช่น message queue และอีเมล หากมี component พิเศษของ user interface ที่แสดงกราฟ แผนที่ และอื่นๆ ที่คล้ายกันซึ่งถูกสร้างขึ้นโดยอัตโนมัติ สิ่งเหล่านี้ก็จะถูก implement ใน infrastructure เช่นกัน