Open Closed

app-nolayers --modern (React, 10.6.1): freshly generated solution fails its own tests/builds — LowCode test isolation, React/Next template defects, docker-compose, multi-tenancy gaps #10902


User avatar
0
merdan created

Provide us with the following info:

ABP Studio solution configuration

  • Template: app-nolayers
  • Template Type: Modern
  • Created ABP Studio Version: 3.1.3
  • Current ABP Studio Version: 3.1.3
  • Multi-Tenancy: Yes
  • UI Framework: react
  • Theme: leptonx
  • Theme Style: system
  • Database Provider: ef
  • Database Management System: postgresql
  • Public Website: Yes
  • Social Login: Yes
  • Include Tests: Yes
  • Use Local References: No
  • Optional Modules: TextTemplateManagement, AuditLogging, OpenIddictAdmin, LowCode
  • Selected Languages: Türkmençe, English, Russian
  • Default Language: Türkmençe
  • Create Command: abp new Ak.Binyat -t app-nolayers --modern --modular --ui-framework react --database-provider ef --database-management-system postgresql --theme leptonx --tests --public-website --without-cms-kit --sample-crud-page --dont-run-install-libs --dont-run-bundling -no-gdpr -no-file-management -no-language-management -low-code

Business modules were then added with ABP Studio (13 modules, e.g. Ak.Binyat.MasterData, Ak.Binyat.Treasury). ABP Framework 10.6.1, .NET 10, macOS. Every defect below shows up on the untouched generated solution; we checked each one against the scaffold commit before changing anything. We have local workarounds for all of them and are reporting so the templates can be fixed.

One related defect is in the open-source template and is already filed on GitHub: abpframework/abp#26221 (the app-nolayers ru.json contains Romanian text).


1. Host tests: LowCode leaks a disposed container between test applications (9 of 10 tests fail)

Exception message and stack trace (every test after the first one in the process):

Volo.Abp.AbpInitializationException : An error occurred during the initialize Volo.Abp.Modularity.OnApplicationInitializationModuleLifecycleContributor phase of the module Volo.Abp.LowCode.AbpLowCodeDomainModule, Volo.Abp.LowCode.Domain, Version=10.6.1.0: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) has already been disposed.
---- System.ObjectDisposedException : Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) has already been disposed.
   at Autofac.Core.Lifetime.LifetimeScope.ThrowDisposedException()
   at Autofac.Core.Lifetime.LifetimeScope.BeginLifetimeScope()
   at Autofac.Extensions.DependencyInjection.AutofacServiceScopeFactory.CreateScope()
   at Volo.Abp.EventBus.IocEventHandlerFactory.GetHandler()
   at Volo.Abp.EventBus.Local.LocalEventBus.GetHandlerFactories(Type eventType)
   ...
   at Volo.Abp.EventBus.Distributed.LocalDistributedEventBus.PublishAsync(Type eventType, Object eventData, Boolean onUnitOfWorkComplete, Boolean useOutbox)
   at Volo.Abp.LowCode.AbpLowCodeApplicationModule.<>c__DisplayClass4_1...MoveNext()
   at Volo.Abp.LowCode.Modeling.DynamicModelManager.NotifyModelChangedAsync()
   at Volo.Abp.LowCode.Modeling.DynamicModelManager.RemoveLayersAsync(Func`2 predicate)
   at Volo.Abp.LowCode.AbpLowCodeDomainModule.OnApplicationInitializationAsync(ApplicationInitializationContext context)
   at Volo.Abp.AspNetCore.TestBase.AbpWebApplicationFactoryIntegratedTest`1..ctor()
   at Ak.Binyat.BinyatTestBase..ctor()

Steps to reproduce: generate the solution with the command above, then run dotnet test Ak.Binyat.Tests. Result: Failed: 9, Passed: 1. Any single test passes when run alone.

Cause (as far as we can see):

  • DynamicModelManager.Instance is a process-wide singleton.
  • AbpLowCodeApplicationModule subscribes an OnModelChanged handler that captures its application's container, and never unsubscribes it on shutdown.
  • The next test application's AbpLowCodeDomainModule initialization calls the previous, disposed application's handler.

Our workaround resets the private Func<Task> backing field of OnModelChanged on DynamicModelManager.Instance to a no-op in the test module's OnApplicationShutdown, using reflection. Setting it to null throws a NullReferenceException instead, because the delegate is invoked without a null check. A supported fix would be to unsubscribe on application shutdown, or to make the manager per-application.

2. Sample CRUD test violates a foreign key (--sample-crud-page)

Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
   at Ak.Binyat.Books.BookAppService_Tests.Should_Create_A_Valid_Book()

(Visible once #1 is worked around.) Book has a required FK to Author, but the test's CreateUpdateBookDto sets no AuthorId. Fix: use a seeded author's id. The generated file name also contains a space: Books/BookAppService_Tests .cs.

3. Module template: sample controller test uses a non-kebab URL for multi-word module names

For a module named MasterData, the route is [Route("api/master-data/example")], but ExampleController_Tests.GetAsync requests api/MasterData/example, so it fails with Shouldly.ShouldAssertException : response.StatusCode. Single-word modules (e.g. Treasury) pass.

4. React (--modern) app

a) Test files cannot load: @testing-library/dom is missing.

src/pages/books/BooksPage.test.tsx(2,35): error TS2305: Module '"@testing-library/react"' has no exported member 'fireEvent'.
src/pages/home/HomePage.test.tsx(2,18): error TS2305: Module '"@testing-library/react"' has no exported member 'screen'.

npx vitest run → Test Files 10 failed (10), no tests. @testing-library/react v16 needs the peer dependency @testing-library/dom, which is not in package.json.

b) tsc -b error:

src/lib/api/books.ts(8,13): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.

export enum BookType is not allowed under erasableSyntaxOnly. The fix is a const object plus a type alias.

c) Eight tests fail once (a) is fixed, because they are out of date with the components:

  • Authors/Books page tests: they look for "Edit"/"Delete" text, but the actions are now in a Radix "Actions" dropdown, rendered only when usePermissions().isGranted(...) is true, and delete goes through a ConfirmDialog.
  • Delete assertions: they expect deleteBook('1'), but TanStack Query v5 passes a second context argument to mutationFn.
  • HomePage test: it expects "Dashboard", which the page no longer renders.
  • axios tests:
    • The 401-retry test's mock never stores the renewed user.
    • The 403 test asserts window.location.href === '/403', which jsdom never changes.

d) Users page: real UI bug. Changing the sort changes the query key, so isLoading turns true and the whole table is replaced by "Please wait…" on every header click. placeholderData: keepPreviousData fixes it. Separately, AppUserAppService.GetListAsync ignores input.Sorting, so the order never changes at all.

e) Localization never loads from the server for a culture that has a static bundle. In src/components/layout/Header.tsx, the effect skips fetchAppLocalization when i18n.hasResourceBundle(currentCulture, 'translation') is true. Because en.json is bundled statically, English never receives server-side resources (e.g. module resources), and adding static bundles for other cultures hides their server strings permanently. The same pattern is in react-public-web.

f) react/Dockerfile cannot build. It runs COPY package*.json + RUN npm ci, but the app is locked with yarn.lock and has no package-lock.json. There is also no .dockerignore, so the host's node_modules is copied into the image.

5. Public website (react-public-web, Next.js 16)

a) next build fails on the generated project:

.next/types/validator.ts(89,31): error TS2344: Type 'typeof import(".../react-public-web/src/pages/home/HomePage")' does not satisfy the constraint 'PagesPageConfig'.
  Property 'default' is missing in type 'typeof import(".../src/pages/home/HomePage")' but required in type 'PagesPageConfig'.
Failed to type check.

The app uses the App Router (src/app/), but keeps a plain component under src/pages/, which Next reserves for Pages-Router routes. Moving it (e.g. to src/views/) fixes the build.

b) yarn lint fails after a build. eslint.config.js ignores only dist, so it lints .next/ output:

.next/server/chunks/ssr/[turbopack]_runtime.js: Definition for rule '@typescript-eslint/no-unused-vars' was not found

c) Every next build rewrites the committed tsconfig.json and next-env.d.ts. It is probably simplest to commit Next's required tsconfig.json values and ignore next-env.d.ts / *.tsbuildinfo, as create-next-app does.

6. Multi-tenancy gaps in generated code (security)

  • AppUser: AppIdentityUserEto (the projection of IdentityUser events into AppUser) carries no TenantId, and AppUser is not IMultiTenant. A tenant administrator calling the users endpoint therefore receives host users and other tenants' users.
  • Sample entities: Book and Author are not IMultiTenant, and their permissions have no MultiTenancySides restriction, so any tenant granted them reads and edits every tenant's data.

7. Docker / scripts (etc/)

  • etc/docker/docker-compose.yml build contexts:
    • The API services use context: ../../, while Dockerfile.local does COPY bin/Release/net10.0/publish/ app/, a path relative to the host project.
    • The web service uses context: ../../../, which is outside the repository.
    • docker compose build fails for both.
  • Wrong environment variables:
    • App_CorsOrigins has a single underscore, so it never binds to App:CorsOrigins.
    • App__HealthCheckUrl=http://binyat:8080/... uses a host that does not exist (the service is binyat-api).
  • PostgreSQL data is lost when the container is recreated: the volume is mounted at /var/opt/postgres, but the official image stores data in /var/lib/postgresql/data.
  • etc/docker/run-docker.ps1: certificate generation is nested inside the certs/ folder-exists check, so a missing localhost.pfx is never regenerated.
  • etc/build/build-images-locally.ps1: it runs npm install / npm run build for React, ignoring yarn.lock and leaving a package-lock.json. The Dockerfile builds the app again anyway.

Steps to reproduce (summary):

  1. Run the create command above (optionally add a module named MasterData in ABP Studio).
  2. dotnet test Ak.Binyat.Tests → 9/10 fail (#1).
  3. In react/: yarn install, then npx tsc -b --noEmit and npx vitest run → #4a/#4b, then #4c.
  4. In react-public-web/: yarn install && yarn build → #5a.
  5. docker build react → #4f. docker compose -f etc/docker/docker-compose.yml build → #7.

We are happy to provide the generated solution or our patches for any of these.

Markdown supported.
Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)

2 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Hi,

    Thanks for the detailed report. We've fixed the template issues, including the multi-tenancy ones: AppUser, Book and Author are now tenant-aware in the generated code. The fix will be in a coming ABP Studio release. The LowCode test issue is in the LowCode module, and we've passed it to the LowCode team.

    There are two things you can apply to your current solution now.

    1. LowCode test isolation

    Other LowCode services also subscribe to DynamicModelManager.OnModelChanged, not only AbpLowCodeApplicationModule. Resetting the backing field to a no-op also removes the handler the manager adds for itself. This version keeps that handler and removes the rest. Put it in BinyatTestModule:

    using System;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Volo.Abp.LowCode.Modeling;
    
    public override void OnApplicationShutdown(ApplicationShutdownContext context)
    {
        _database?.Dispose();
        RemoveLowCodeModelChangedHandlers();
    }
    
    private static void RemoveLowCodeModelChangedHandlers()
    {
        var manager = DynamicModelManager.Instance;
        var handlers = typeof(DynamicModelManager)
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
            .Single(f => f.FieldType == typeof(Func<Task>))
            .GetValue(manager) as Func<Task>;
    
        if (handlers == null)
        {
            return;
        }
    
        foreach (var handler in handlers.GetInvocationList().Cast<Func<Task>>())
        {
            if (!ReferenceEquals(handler.Target, manager))
            {
                manager.OnModelChanged -= handler;
            }
        }
    }
    

    2. AppUser tenant isolation

    The options.EtoMappings.Add<IdentityUser, AppIdentityUserEto>() line in BinyatModule replaces Identity's own IdentityUser to UserEto mapping. So besides the missing TenantId, the UserEto events are never published, and the permission grants of a deleted user are not cleaned up. To fix it:

    • Remove that EtoMappings.Add line, the AppIdentityUserEto class and its mapper in BinyatMappers.
    • Change AppUserSyncHandler to handle EntityCreatedEto<UserEto>, EntityUpdatedEto<UserEto> and EntityDeletedEto<UserEto>. Volo.Abp.Users.UserEto already has TenantId.
    • Make AppUser multi-tenant, and pass TenantId when you create it in AppUserSyncHandler (identityUser.TenantId from UserEto) and in AppUserSeedBootstrapper:
    public class AppUser : AuditedAggregateRoot<Guid>, IMultiTenant
    {
        public Guid? TenantId { get; private set; }
    
        public AppUser(
            Guid id,
            string userName,
            string? email,
            string? name,
            string? surname,
            string? phoneNumber,
            bool isActive,
            Guid? tenantId)
            : base(id)
        {
            TenantId = tenantId;
            UserName = Check.NotNullOrWhiteSpace(userName, nameof(userName), maxLength: AppUserConsts.MaxUserNameLength);
            Update(email, name, surname, phoneNumber, isActive);
        }
    
        // ...
    }
    
    • Add a migration for the new column, and fill TenantId of the existing rows in the same migration. Without this, the existing tenant users stay under the host, and the tenant data seeding fails with a duplicate key error:
    migrationBuilder.AddColumn<Guid>(
        name: "TenantId",
        table: "AppUsers",
        type: "uuid",
        nullable: true);
    
    migrationBuilder.Sql(
        @"UPDATE ""AppUsers"" AS a SET ""TenantId"" = u.""TenantId"" FROM ""AbpUsers"" AS u WHERE u.""Id"" = a.""Id"";");
    
    • Update AppUserSyncHandler_Tests to use UserEto instead of AppIdentityUserEto.

    Thanks

    Markdown supported.
    Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Hi,

    We've refunded your ticket.

    Thanks

    Markdown supported.
    Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)
Boost Your Development
ABP Live Training
Packages
See Trainings
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v10.8.0-preview. Updated on October 05, 2026, 11:32
1
ABP Assistant
🔐 You need to be logged in to use the chatbot. Please log in first.