Logo Ioc Development Pattern

Ioc Development Pattern

Cộng đồng
scottdurow
ioc-development-pattern

Inversion of Control (IoC) development pattern for building apps with in-memory test data first, then swapping to real data sources. Covers service interfaces, domain models with DTOs, in-memory implementations, service registry, React Query (TanStack Query) integration with cache invalidation, error handling, and incremental backend migration. Triggers on "IoC", "inversion of control", "in-memory data", "mock data", "test data first", "service interface", "swap implementation", "local development pattern", "dev without dataverse", "dev without database", "develop locally", "mock service", "in-memory service", "service abstraction", "data service pattern", "service layer", "react query", "tanstack query", "query key factory", "cache invalidation", "optimistic update", "domain model", "dto pattern".

Tổng quan

Nhà phát hànhscottdurow
Kho mãpower-platform-full-stack-skills
Tên kỹ năngioc-development-pattern
Sao
39
Bản fork
10
Tệp đi kèm
5
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 5 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được scottdurow công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Ioc Development Pattern trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/scottdurow/power-platform-full-stack-skills/tree/main/skills/ioc-development-pattern
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/scottdurow/power-platform-full-stack-skills.git /tmp/power-platform-full-stack-skills
mkdir -p .claude/skills
cp -r /tmp/power-platform-full-stack-skills/skills/ioc-development-pattern .claude/skills/ioc-development-pattern
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Ioc Development Pattern trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Ioc Development Pattern ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Ioc Development Pattern không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

IoC Development Pattern

Build your entire UI against in-memory test data first. Connect to real data sources later.

This pattern applies to any Power Platform frontend — Code Apps (Dataverse, Azure SQL), Power Pages code sites (Dataverse Web API), or any app that consumes external data.

Why This Pattern

  • Fast local iteration — No network calls, no auth, no environment setup needed during UI development
  • Demo without infrastructure — Show working UI to stakeholders before any backend exists
  • Testable — In-memory implementations double as test fixtures
  • Clean separation — Components depend on interfaces, not backends. Swap data sources without touching UI code
  • Incremental migration — Connect one entity at a time; mix in-memory and real services during transition

Step 1: Define Service Interfaces and Domain Models

Create a TypeScript interface for each data entity your app needs. The interface describes what the app needs, not how any specific backend works.

Base Service Interface

typescript
// src/services/interfaces.ts

export interface IEntityService<T> {
  getAll(options?: QueryOptions): Promise<T[]>;
  getById(id: string): Promise<T | null>;
  create(entity: Omit<T, "id">): Promise<T>;
  update(id: string, changes: Partial<T>): Promise<void>;
  delete(id: string): Promise<void>;
}

export interface QueryOptions {
  filter?: string;
  orderBy?: string;
  top?: number;
  select?: string[];
}

Domain Model Types

Each domain entity gets three type definitions:

  1. Domain model — what the app works with (full shape with proper types)
  2. CreateDto — fields for creating a new record (only user-controlled fields)
  3. UpdateDto — fields for updating (all optional, only include what changed)
  4. Filters — query parameters for list operations
typescript
// src/features/projects/models/Project.ts

/** Domain model — what the app works with */
export interface Project {
  id: string;
  name: string;
  description: string | null;
  status: "Active" | "Completed" | "On Hold";
  startDate: Date;
  budget: number;
  createdOn: Date;
  modifiedOn: Date;
}

/** Fields for creating a new record — only user-controlled fields */
export interface CreateProjectDto {
  name: string;
  description?: string;
  status?: Project["status"];
  startDate?: Date;
  budget?: number;
}

/** Fields for updating — all optional, only include what changed */
export interface UpdateProjectDto {
  name?: string;
  description?: string;
  status?: Project["status"];
  startDate?: Date;
  budget?: number;
}

/** Query filters */
export interface ProjectFilters {
  status?: Project["status"];
  search?: string;
}

Entity Service Interface

typescript
// src/services/interfaces.ts (continued)

export interface IProjectService extends IEntityService<Project> {
  getByStatus(status: Project["status"]): Promise<Project[]>;
}

export interface ITaskService extends IEntityService<Task> {
  getByProject(projectId: string): Promise<Task[]>;
}

DTO Design Principles

  • CreateDto contains ONLY fields the user controls — never IDs, ownership, state codes, or timestamps
  • UpdateDto has all fields optional — only include what changed
  • Domain model has proper types (Date not string, boolean not number, enums not raw strings)
  • Design the interface around your app's needs, not the backend's shape. The implementation handles translation between your domain types and the backend's raw types

Pagination Interface (Design from Day 1)

Include pagination in your service interface from the start — don't bolt it on later:

typescript
interface PageOptions {
  page: number;
  pageSize: number;
  sortField?: string;
  sortDirection?: 'asc' | 'desc';
  search?: string;
  filter?: Record<string, string>;
}

interface PagedResult<T> {
  items: T[];
  totalCount: number;
  page: number;
  pageSize: number;
}

interface IEntityService<T> {
  getPage(options: PageOptions): Promise<PagedResult<T>>;
  getStatusCounts(): Promise<Record<string, number>>;
  getById(id: string): Promise<T | null>;
  create(dto: CreateDto): Promise<T>;
  update(id: string, dto: UpdateDto): Promise<T>;
  delete(id: string): Promise<void>;
}

Known Platform Limitations:

  • Dataverse OData (Code Apps): $skip is supported via the generated service's IGetAllOptions. Use skip + top for standard server-side paging, or skipToken for continuation-based paging.
  • Power Pages Web API: $skip is NOT supported on the /_api/ endpoint. Use FetchXML paging instead — FetchXML supports page and count attributes for true server-side pagination, plus a paging-cookie for efficient continuation. Wrap FetchXML queries via /_api/ using ?fetchXml=<encoded-xml>.

NON-NEGOTIABLE: Server-Side Data Delegation

If the user will see sorted, filtered, or paginated data — the server must do the sorting, filtering, and paginating. The client only renders what the server returns. No exceptions.

These rules are MANDATORY for every service implementation and every list/grid screen. Violations cause wrong data, wrong counts, and systems that break at scale.

Rule 1: Sorting MUST be server-side
typescript
// BAD — client-side sort only sorts the current page
const sorted = [...items].sort((a, b) => a.price - b.price);

// GOOD — sort parameter sent to server
list(filters, page, pageSize, sortColumn: "price", sortDirection: "asc")
// Server adds: $orderby=zava_price asc

Why: Sorting 25 items on page 1 does NOT produce the same result as sorting the entire 10,000-row dataset and returning the first 25. Client-side sort is a lie when pagination is active.

In-memory implementation exception: In-memory services hold all data in arrays, so sorting the array then slicing for pagination is correct. But the interface MUST accept sort parameters so that real implementations can delegate to the server.

Rule 2: Filtering MUST be server-side
typescript
// BAD — fetch all, filter in browser
const all = await service.list({}, 1, 1000);
const filtered = all.items.filter(x => x.status === "Active");

// GOOD — filter parameter sent to server
const result = await service.list({ status: "Active" }, 1, 25);
// Server adds: $filter=statuscode eq 1

Why: Client-side filtering makes totalCount wrong. If the server says 100 records total but only 12 match the filter, the pagination shows 4 pages but pages 2-4 are empty. Users see ghost pages.

corollary: Every filter on the UI MUST have a corresponding server-side query parameter. If the server can't filter by a field, either:

  1. Add that field to the server query (preferred), or
  2. Remove the filter from the UI (acceptable), or
  3. Document it as a known limitation with a clear comment (last resort)

Never silently filter client-side and pretend the pagination is correct.

Rule 3: Pagination MUST be server-side
typescript
// BAD — fetch all, slice in browser
const all = await fetch("/api/properties");       // returns 10,000 rows
const page = all.slice((pageNum - 1) * 25, pageNum * 25);

// GOOD — page parameters sent to server
const result = await fetch("/api/properties?$top=25&$skip=50");  // returns 25 rows

Why: Fetching 10,000 records to display 25 wastes bandwidth, memory, and time. Response times degrade linearly with dataset size.

When true server-side paging isn't possible (e.g., Dataverse OData lacks $skip):

  • Use $skiptoken continuation-based paging
  • Use FetchXML page + count attributes
  • Use over-fetch + slice ONLY as a documented last resort with a hard cap (e.g., max 500 rows)
  • NEVER silently over-fetch without documenting the limitation
Rule 4: Search/text queries MUST be server-side
typescript
// BAD — client-side text search
const results = items.filter(x =>
  x.name.toLowerCase().includes(searchText.toLowerCase())
);

// GOOD — search sent to server
const result = await service.list({ search: searchText }, 1, 25);
// Server adds: $filter=contains(zava_name, 'searchText')

Why: Client-side search only searches the current page. A user searching for "Penthouse" won't find it if it's on page 4 and they're viewing page 1.

Rule 5: Counts and aggregates MUST be server-side
typescript
// BAD — fetch all records to count them
const all = await service.list({}, 1, 99999);
const activeCount = all.items.filter(x => x.status === "Active").length;

// GOOD — use server-side count or aggregate
const counts = await service.getStatusCounts();
// Server uses: GET /api/properties?$count=true&$filter=statuscode eq 1
// Or: FetchXML aggregate queries

Why: Loading 10,000 records to display a dashboard number "Active: 47" is catastrophically wasteful. Dashboard screens with multiple KPIs multiply the problem.

Rule 6: The service interface MUST express server-side capabilities

Every list method in the service interface MUST accept:

  • filters — typed filter object (not any)
  • page and pageSize — pagination parameters
  • sortColumn and sortDirection — sort parameters
  • search — text search parameter (if the entity supports it)
typescript
// GOOD — interface makes delegation explicit
interface IPropertyService {
  list(
    filters?: PropertyFilters,
    page?: number,
    pageSize?: number,
    sortColumn?: string,
    sortDirection?: SortDirection
  ): Promise<PagedResult<Property>>;
}

If a parameter exists in the interface, BOTH the in-memory AND real implementations MUST honor it. The in-memory implementation sorts/filters/pages its arrays. The real implementation delegates to the server.

Verification Checklist

Before marking any list screen as complete, verify:

  • Sort column + direction are sent to the service layer (not sorted after fetch)
  • All active filters are sent to the service layer (not filtered after fetch)
  • Page number + page size are sent to the service layer (not sliced after fetch)
  • totalCount in PagedResult reflects the filtered count, not the total table size
  • Text search is sent to the service layer (not searched after fetch)
  • Dashboard counts use server-side aggregation, not fetch-all-and-count
  • The in-memory implementation honors ALL the same parameters as the real implementation
  • No Array.prototype.sort() or .filter() on fetched PagedResult.items in screen components
  • React Query hooks for paged data use placeholderData: keepPreviousData
  • Both in-memory and real service have matching SORT_FIELDS / SORT_MAP keyed by DataGrid columnId
  • Detail screen hooks expose isLoading, isError, and data separately (not combined into one check)
  • Every mutation onSuccess calls useNotificationStore.getState().enqueue() with a success message
  • Every mutation onError calls useNotificationStore.getState().enqueue() with an error message
  • In-memory sort uses typed accessor SORT_FIELDS map (not generic string-key bracket notation)
Rule 7: Sort Map Contract Between UI and Service

The DataGrid columnId values are the contract between UI columns and service sort logic. Both in-memory and real implementations MUST define a map from these IDs to their sort mechanism.

typescript
// In-memory: map columnId → accessor function
const SORT_FIELDS: Record<string, (item: Entity) => string | number | Date> = {
  title: (p) => p.name.toLowerCase(),
  price: (p) => p.price,
  status: (p) => p.status,
};

// Real (Dataverse): map columnId → OData column name
private static SORT_MAP: Record<string, string> = {
  title: "prefix_name",
  price: "prefix_price",
  status: "statuscode",
};

Why two maps? The in-memory service sorts arrays using accessor functions. The Dataverse service builds $orderby clauses using column names. Both are keyed by the same columnId strings from the DataGrid, so the UI never knows which implementation is active.

Default sort: When sortColumn is not in the map, fall back to a sensible default (e.g., modifiedOn desc). Never throw or return unsorted data.

Rule 8: Client-Side Search — Last Resort with Correct Pagination

Some searches are impossible server-side (e.g., OData cannot contains() on lookup display names). When client-side filtering is unavoidable:

  1. Document it with a comment: // Client-side: OData can't filter on lookup display names
  2. Fix the pagination count — use the filtered length, not totalCount:
tsx
// Client-side search on returned items (documented limitation)
const filteredItems = useMemo(() => {
  if (!search) return data?.items ?? [];
  const q = search.toLowerCase();
  return (data?.items ?? []).filter(item =>
    item.displayName?.toLowerCase().includes(q)
  );
}, [data, search]);

// Pagination uses filtered count when client-side search is active
<Pagination
  totalItems={search ? filteredItems.length : data?.totalCount ?? 0}
  ...
/>
  1. Never use client-side search as the default approach — it only searches the current page. Exhaust server-side options first.

Mock Data Indicator

When the app is running with in-memory mock data, display a visible indicator:

tsx
// In your AppShell or TopBar component:
{serviceRegistry.isUsingMockData && (
  <Badge appearance="tint" color="warning">MOCK DATA</Badge>
)}

This prevents confusion during testing and demos. The user should always know whether they're looking at real or simulated data.


Service Boundary Validation Rules

Data entering the app from external sources (APIs, AI services, user input) must be validated and normalized at the service boundary before reaching the UI layer.

  1. Clamp numeric values from external APIs — AI-generated scores, ratings, or computed values can exceed expected ranges (e.g., a score of 105 when the UI expects 0–100). Clamp at the service mapper, not in the component:

    typescript
    // In the domain mapper (service layer):
    score: Math.max(0, Math.min(100, raw.aiScore ?? 0)),
  2. Wrap JSON.parse of external API responses in try/catch — External APIs may return malformed JSON, HTML error pages, or empty bodies. Always catch parse errors and throw a user-friendly error:

    typescript
    let parsed: ExternalResponse;
    try {
      parsed = JSON.parse(responseText);
    } catch {
      throw new Error("Invalid response from external service");
    }
  3. Date formatting: use toISOString(), never String() — String(dateObject) produces non-ISO format like "Sat Feb 01 2026 00:00:00 GMT..." which is unparseable by many backends. Always use date instanceof Date ? date.toISOString() : date for reliable serialization.

  4. Date-only fields: append T00:00:00 for local-time interpretation — When saving a date-only value (e.g., a closing date), append T00:00:00 to the ISO string to prevent UTC interpretation that shifts the date backward in negative-offset timezones.

  5. InMemory services: resolve lookup display names via lazy import — When an in-memory create() or update() method needs to resolve a lookup ID to a display name (e.g., to populate a categoryName field), use lazy import() of the service registry to prevent circular module dependencies:

    typescript
    async create(dto: CreateDto): Promise<Entity> {
      // Lazy import to break circular dependency
      const { getService } = await import("../serviceRegistry");
      const categoryService = getService("categories");
      const category = await categoryService.getById(dto.categoryId);
      // ... populate entity with category.name
    }

Step 2: Build In-Memory Implementations

Create implementations that store data in arrays. These run entirely in the browser with zero external dependencies.

See resources/in-memory-implementation.md for the full InMemoryProjectService class implementing all interface methods with array storage.

Test Data Guidelines

  • Seed enough records to test pagination, empty states, and scrolling (10–50 records)
  • Include edge cases — empty strings, long names, special characters, null-like values
  • Cover all enum values — ensure every status/category has at least one record
  • Use realistic values — stakeholders will see this data in demos
  • Optionally simulate latency — add await new Promise(r => setTimeout(r, 200)) at the top of methods to test loading states and spinners

Step 3: Create a Service Registry

Centralize service resolution so the app consumes interfaces, not implementations. One swap point controls which implementations are active.

Simple Factory Pattern

typescript
// src/services/serviceRegistry.ts

import type { IProjectService, ITaskService } from "./interfaces";
import { InMemoryProjectService } from "./in-memory/InMemoryProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";

// --- Swap point: change these imports when connecting real backends ---
// import { DataverseProjectService } from "./dataverse/DataverseProjectService";
// import { AzureSqlProjectService } from "./azure-sql/AzureSqlProjectService";

const services = {
  projects: new InMemoryProjectService() as IProjectService,
  tasks: new InMemoryTaskService() as ITaskService,
};

export function getService<K extends keyof typeof services>(name: K): (typeof services)[K] {
  return services[name];
}

// --- Test isolation: reset singleton state between tests ---
export function _resetForTesting(): void {
  services.projects = new InMemoryProjectService();
  services.tasks = new InMemoryTaskService();
}

Test isolation is critical. The registry uses module-level singletons — state persists between tests unless explicitly reset. Always call _resetForTesting() in beforeEach() during unit tests. See resources/testing-strategy.md for full testing patterns.

React Context Pattern (Alternative)

For React apps, a context provider gives components access to services via hooks:

typescript
// src/services/ServiceContext.tsx

import { createContext, useContext, type ReactNode } from "react";
import type { IProjectService, ITaskService } from "./interfaces";
import { InMemoryProjectService } from "./in-memory/InMemoryProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";

interface Services {
  projects: IProjectService;
  tasks: ITaskService;
}

const defaultServices: Services = {
  projects: new InMemoryProjectService(),
  tasks: new InMemoryTaskService(),
};

const ServiceContext = createContext<Services>(defaultServices);

export function ServiceProvider({ children, services }: { children: ReactNode; services?: Partial<Services> }) {
  const merged = { ...defaultServices, ...services };
  return <ServiceContext.Provider value={merged}>{children}</ServiceContext.Provider>;
}

export function useServices(): Services {
  return useContext(ServiceContext);
}

Usage in components:

typescript
const { projects } = useServices();
const allProjects = await projects.getAll({ top: 50 });

Step 4: Build the UI Against Interfaces

All components import from the service registry or context — never from a concrete implementation. This means the entire UI can be built, tested, and demoed with zero backend connectivity.

Simple Approach (useState + useEffect)

typescript
// src/components/ProjectList.tsx — uses the interface, not the backend

import { useEffect, useState } from "react";
import { useServices } from "../services/ServiceContext";
import type { Project } from "../services/interfaces";

export function ProjectList() {
  const { projects } = useServices();
  const [items, setItems] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    projects.getAll({ orderBy: "name asc", top: 50 }).then((data) => {
      setItems(data);
      setLoading(false);
    });
  }, [projects]);

  if (loading) return <div>Loading...</div>;

  return (
    <ul>
      {items.map((p) => (
        <li key={p.id}>{p.name} — {p.status}</li>
      ))}
    </ul>
  );
}

Preferred: React Query (TanStack Query) Integration

For production React apps, use React Query (@tanstack/react-query) instead of raw useEffect. It provides caching, background refetching, loading/error states, and mutation hooks out of the box.

bash
npm install @tanstack/react-query

Wrap your app with QueryClientProvider:

tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      retry: 1,
    },
  },
});

export const App = () => (
  <QueryClientProvider client={queryClient}>
    {/* app content */}
  </QueryClientProvider>
);

See resources/react-query-hooks.md for the complete React Query integration: query key factory, query hooks, mutation hooks with cache invalidation, optimistic updates, and component usage patterns.

At this stage you have a fully functional app running on in-memory data. Iterate on the UI, get stakeholder feedback, refine flows — all without touching a backend.


Step 5: Implement Real Backend Services

When the UI is approved and stable, create implementations that connect to the real data source. The implementation translates between your domain interface and the backend's raw API.

Service Implementation Pattern

Every real service method should:

  1. Validate required inputs before calling the API
  2. Call the platform API with properly mapped payloads
  3. Transform the raw response to domain model types via toDomainModel()
  4. Catch errors and throw user-friendly messages
  5. Log the raw error for debugging

See resources/real-service-implementation.md for the complete RealProjectService class, key implementation principles, and graceful degradation patterns. For platform-specific implementation guidance:

  • Dataverse (Code Apps): Read ../power-apps-code-apps/resources/dataverse-integration.md
  • Azure SQL (Code Apps): Read ../power-apps-code-apps/resources/connector-azure-sql.md
  • Power Pages Web API: Read ../power-pages/resources/webapi-integrate.md

Step 6: Swap to Real Services

Update the service registry to use the real implementations. You can swap all at once or incrementally — one entity at a time:

typescript
// src/services/serviceRegistry.ts — after connecting Dataverse

import type { IProjectService, ITaskService } from "./interfaces";
import { RealProjectService } from "./real/RealProjectService";
import { InMemoryTaskService } from "./in-memory/InMemoryTaskService";

const services = {
  projects: new RealProjectService() as IProjectService,    // ← swapped
  tasks: new InMemoryTaskService() as ITaskService,          // ← still in-memory
};

export function getService<K extends keyof typeof services>(name: K): (typeof services)[K] {
  return services[name];
}

No UI code changes needed. Components still call projects.getAll() — the registry routes to the real implementation.


When to Swap

  1. Build UI first — Get full UX approval on in-memory data
  2. Set up the data source — Create Dataverse tables, Azure SQL stored procedures, etc.
  3. Implement one service — Start with the most critical entity
  4. Test the swap — Verify data flows correctly, handle edge cases in real data
  5. Swap remaining services — One at a time until fully connected
  6. Remove in-memory implementations — Or keep them for unit tests

Validation at Each Step

After completing each step, run npm run build (or npx tsc --noEmit) to verify there are no type errors. Fix any errors before proceeding to the next step. After Step 4, run the app (npm run dev) and manually verify the in-memory data renders correctly.

Important Notes

  • Keep interfaces stable — Once the UI is built against an interface, changing it requires updating all implementations. Design interfaces carefully upfront.
  • In-memory implementations are test fixtures — Reuse them in unit tests. They're fast, deterministic, and require no mocking libraries.
  • Don't over-engineer the registry — A simple factory or context provider is sufficient for most apps. You don't need a full DI container.
  • Test data should cover edge cases — Empty lists, long strings, special characters, maximum field lengths, null/undefined values, all enum variants.
  • Map types at the boundary — Real implementations should translate between backend types (e.g., all-string Dataverse models, ResultSets wrappers from Azure SQL) and your clean domain types. Components never deal with raw backend shapes.
  • Error handling in the interface — Decide upfront whether methods throw or return error objects. Be consistent across all implementations.

NON-NEGOTIABLE: Detail Screen Data Loading

Detail screens (record forms) MUST distinguish between loading, error, and not-found states. Combining them into a single check causes infinite spinners when a record doesn't exist.

The Bug

tsx
// BAD — infinite spinner when record doesn't exist
const { data: property, isLoading } = useProperty(id);
if (isLoading || !property) return <Spinner label="Loading..." />;

When id is valid but the record was deleted, isLoading becomes false and data is null. The !property check keeps showing the spinner forever — the user has no way to know the record doesn't exist.

The Fix

tsx
const { data: property, isLoading, isError } = useProperty(id);

if (isLoading) return <Spinner label="Loading property..." />;

if (isError || !property) {
  return (
    <MessageBar intent="error">
      <MessageBarBody>
        Property not found. It may have been deleted.
        <Button appearance="subtle" onClick={() => navigate("/properties")}>
          Back to list
        </Button>
      </MessageBarBody>
    </MessageBar>
  );
}

Rule

Every detail screen MUST have THREE distinct states:

  1. Loading — isLoading is true → show Spinner
  2. Error / Not Found — isError or data is null → show error message with back navigation
  3. Loaded — data is available → render the form

Never combine loading and not-found into one conditional.


Resource Files

ResourceDescription
resources/in-memory-implementation.mdFull InMemoryProjectService reference implementation with array storage
resources/react-query-hooks.mdQuery key factory, query/mutation hooks, cache invalidation, optimistic updates, component usage
resources/real-service-implementation.mdFull RealProjectService class, toDomainModel(), implementation principles, graceful degradation
resources/testing-strategy.mdTesting patterns for the IoC service layer — unit testing in-memory and real services, testing React Query hooks, service registry test isolation, Vitest configuration
resources/error-handling.mdStructured error handling pattern — typed errors, error boundary integration, React Query error states, toast notifications

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Ioc Development Pattern làm được gì?

Inversion of Control (IoC) development pattern for building apps with in-memory test data first, then swapping to real data sources. Covers service interfaces, domain models with DTOs, in-memory implementations, service registry, React Query (TanStack Query) integration with cache invalidation, error handling, and incremental backend migration. Triggers on "IoC", "inversion of control", "in-memory data", "mock data", "test data first", "service interface", "swap implementation", "local development pattern", "dev without dataverse", "dev without database", "develop locally", "mock service",...

Vì sao nên dùng Ioc Development Pattern trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Ioc Development Pattern là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Ioc Development Pattern trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/scottdurow/power-platform-full-stack-skills/tree/main/skills/ioc-development-pattern. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Ioc Development Pattern?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Ioc Development Pattern với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Ioc Development Pattern với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Ioc Development Pattern có miễn phí không?

Kỹ năng này được scottdurow phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇