@ -0,0 +1,60 @@ |
|||
# .NET Conf China 2025: Changing the World, Changing Ourselves - See You Again in Shanghai |
|||
|
|||
 |
|||
|
|||
.NET Conf China 2025 is an annual community event for developers, celebrating the release of .NET 10 (LTS) and the achievements of the past year in China. As an extension of .NET Conf 2025, this event brings together local tech communities, well-known companies, and open-source organizations. It has become the largest .NET online and offline conference in China, dedicated to spreading .NET technology in Chinese and fostering collaboration and exchange. |
|||
|
|||
## Event Highlights: Key Topics and Takeaways |
|||
|
|||
This year’s conference focused on three main themes: performance improvements, AI integration, and cross-platform development. Topics covered how to achieve performance gains while maintaining engineering quality, balancing between multi-platform consistency and native capabilities, and taking generative AI from “demo-level” to “production-ready.” On the community and ecosystem side, the event showcased the .NET Foundation’s and domestic and international companies’ progress in supporting architectures like ARM, LoongArch, and RISC-V. It also highlighted best practices in DevOps, observability, and engineering toolchains, creating a complete path from ideas to implementation. |
|||
|
|||
### Opening Keynote |
|||
|
|||
Scott Hanselman kicked off .NET Conf China 2025 with a video keynote, announcing that .NET 10 is now available on the official website. He framed the release around four pillars—AI, cloud-native, cross-platform, and performance—including integration with the Microsoft Agent Framework for building and orchestrating multi-agent systems in .NET/C#, industry-leading container and Kubernetes support with .NET Aspire simplifying local containerized development, a richer cross-platform desktop ecosystem (.NET MAUI, Avalonia, Uno Platform), and major performance gains such as Native AOT and single-file publishing for faster startup and easier distribution across platforms. |
|||
|
|||
He underscored China’s importance as .NET’s second-largest market, with roughly 13% of users, and noted that generative AI usage in China has doubled in 2025. The local community is seeing strong momentum around ML.NET, .NET Aspire, and the C# Dev Kit in VS Code. Reflecting on his Baby Smash game written 20 years ago, which now runs cross-platform on .NET 10, he called on developers to modernize: move existing Web, WinForms, and WPF apps to the cloud, improve performance, ship as a single executable, and weave in AI capabilities. |
|||
|
|||
On AI, he emphasized a human-centered stance: AI and agents should augment, not replace, developers. In the future, developers will orchestrate and govern agents, and human judgment will matter more than ever. He closed by thanking the open-source community for its many proposals and pull requests, stressing that .NET is an open-source platform built together by Microsoft and the community, and wishing everyone an inspiring conference and a joyful journey with .NET 10. |
|||
|
|||
 |
|||
|
|||
### Roundtable Discussion |
|||
|
|||
The roundtable discussion, titled “Empowering with AI, Breaking Through Cross-Platform Barriers, and Ecosystem Innovation,” focused on practical implementation. It explored typical paths for large models and intelligent agents in enterprises, key considerations for choosing cross-platform UI frameworks, and the evolution of these frameworks. Panelists discussed questions like: How can AI capabilities be integrated into existing business processes instead of creating an “experimental” pipeline? How should cross-platform solutions be evaluated in terms of performance, ecosystem, and team skillsets? What are the unique opportunities for domestic ecosystems in the global tech landscape? And how can community collaboration help developers quickly adopt best practices? A shared consensus emerged: in the short term, focus on running scenarios; in the long term, return to engineering fundamentals. Both toolchains and methodologies are equally important. |
|||
|
|||
 |
|||
|
|||
### In-Depth Sessions |
|||
|
|||
The afternoon featured four breakout sessions, covering a wide range of topics with deep dives into both foundational technologies and real-world project reviews: |
|||
|
|||
- **Frontend and Cross-Platform:** Focused on the progress of Avalonia, Blazor, and WebAssembly, as well as the integrated experience of .NET Aspire in multi-service applications. Speakers shared insights on reusing core logic between desktop and web, shortening cold start times with incremental compilation and resource trimming, and performance profiling and optimization in WASM scenarios. |
|||
- **AI Agents and Enterprise Adoption:** Discussed multi-agent orchestration, the MCP plugin ecosystem, and enterprise data compliance. From common pitfalls of “demo-level” AI to the “five-step method” for moving from POC to production, the session covered use cases like knowledge retrieval, process automation, intelligent customer service, and developer assistants, emphasizing evaluation metrics, prompt engineering, and monitoring governance. |
|||
- **.NET Practices and Engineering:** Focused on the latest capabilities and performance practices of EF Core, the boundaries of NativeAOT, automated testing strategies, and observability implementation. Discussions included database migration strategies, caching and concurrency control for hot paths, end-to-end tracing, and structured logging. |
|||
- **Solutions and Case Studies:** From Clean Architecture/DDD to AI-powered business evolution, topics included application modernization, SaaS transformation, and edge-cloud collaboration in AIoT. Speakers broke down modular governance, team collaboration, and release strategies for complex systems, putting “delivering value continuously” at the center stage. |
|||
|
|||
 |
|||
|
|||
## ABP Booth Highlights: Showcases, Conversations, and Fun |
|||
|
|||
The story of ABP began with a promise to create a better starting point. From the frustration of “copy-pasting boilerplate code,” we crafted a modular, opinionated framework. We chose open source and community collaboration. We founded Volosoft to turn our vision into reality with professional tools. Today, tens of thousands of developers explore the ABP framework, and thousands of teams rely on the ABP platform to deliver production-grade .NET applications faster and more securely. |
|||
|
|||
 |
|||
|
|||
At .NET Conf China 2025, we brought our “developer platform built for developers” to every visitor. Our booth demonstrations started with “a production-ready skeleton from the start”: modular layered architecture, built-in authentication and authorization systems, multi-tenancy support, audit logging, and localization—all out of the box. On the frontend and backend, ABP offers diverse options like MVC, Blazor, and Angular, enabling teams to quickly implement solutions on familiar stacks while maintaining flexibility for future evolution. We also showcased how ABP integrates with containerization, CI/CD, and observability, emphasizing “engineering built into the framework, not reinvented by every team.” |
|||
|
|||
 |
|||
|
|||
**Interaction and Prizes:** Sharing technology should also be warm and engaging. We hosted a QR code raffle at the booth, with prizes including ABP stickers, the book *Mastering ABP Framework*, and Bluetooth headphones. Multiple rounds of raffles and group photos made the interactions more memorable. Many developers shared their ABP experiences and plans for improvement right at the booth, and a few impromptu “code walkthroughs” naturally happened. The love and joy for technology were captured in every handshake and discussion. |
|||
|
|||
 |
|||
|
|||
## Looking Ahead: Building the Ecosystem Together |
|||
|
|||
From an open-source journey to a complete development platform for the future, we’ve always believed that developers deserve a better starting point. Around performance, intelligence, and cross-platform capabilities, we will continue investing in engineering, ecosystem collaboration, and best practice sharing. We also welcome more partners to contribute through documentation and examples, share your experiences, and submit your ideas. Together, let’s make “useful infrastructure” more stable, efficient, and business-friendly. |
|||
|
|||
We look forward to exchanging ideas, sharing practices, and building the ecosystem together at the next gathering. Technology meets creativity, and the possibilities are endless. We’re on the road and waiting for you at the next event. |
|||
|
|||
See you next year at .NET Conf China 2026! |
|||
|
|||
 |
|||
|
After Width: | Height: | Size: 396 KiB |
|
After Width: | Height: | Size: 502 KiB |
|
After Width: | Height: | Size: 432 KiB |
|
After Width: | Height: | Size: 328 KiB |
|
After Width: | Height: | Size: 524 KiB |
|
After Width: | Height: | Size: 378 KiB |
|
After Width: | Height: | Size: 671 KiB |
|
After Width: | Height: | Size: 399 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 7.5 KiB |
@ -0,0 +1,797 @@ |
|||
# Implement Automatic Method-Level Caching in ABP Framework |
|||
|
|||
Caching is one of the most effective ways to improve application performance, but implementing it manually for every method can be tedious and error-prone. What if you could cache method results automatically with just an attribute? In this article, we'll explore how to build an automatic method-level caching system in ABP Framework that handles cache invalidation, supports multiple scopes, and integrates seamlessly with your existing application. |
|||
|
|||
By the end of this guide, you'll understand how to implement attribute-based caching that automatically invalidates when entities change, supports user-specific and global caching scopes, and provides built-in metrics for monitoring cache performance. |
|||
|
|||
> 💡 **Complete Implementation Available**: This article is based on a working demo project. You can find the complete implementation in the [AbpAutoCacheDemo repository](https://github.com/salihozkara/AbpAutoCacheDemo), with the core AutoCache library implementation available in [this commit](https://github.com/salihozkara/AbpAutoCacheDemo/commit/946df1fc07de6eddd26eb14013a09968cd59329b). |
|||
|
|||
## What is Automatic Method-Level Caching? |
|||
|
|||
Automatic method-level caching is a technique that intercepts method calls and caches their results without requiring manual cache management code. Instead of writing cache logic in every method, you simply decorate methods with attributes that define caching behavior. |
|||
|
|||
 |
|||
|
|||
The key benefits include: |
|||
|
|||
- **Reduced Boilerplate:** No repetitive cache management code in your business logic |
|||
- **Consistent Caching Strategy:** Centralized cache configuration and behavior |
|||
- **Smart Invalidation:** Automatic cache clearing when related entities change |
|||
- **Multiple Scopes:** Support for global, user-specific, and entity-specific caching |
|||
- **Built-in Monitoring:** Track cache hits, misses, and performance metrics |
|||
|
|||
## Architecture Overview |
|||
|
|||
The automatic caching system consists of several key components working together: |
|||
|
|||
 |
|||
|
|||
**Core Components:** |
|||
|
|||
1. **CacheAttribute:** The attribute you apply to methods to enable automatic caching |
|||
2. **AutoCacheInterceptor:** Intercepts method calls and handles cache operations |
|||
3. **AutoCacheManager:** Manages cache storage, retrieval, and key generation |
|||
4. **IAutoCacheKeyManager:** Handles cache key mapping and invalidation |
|||
5. **AutoCacheInvalidationHandler:** Listens to entity changes and clears related caches |
|||
|
|||
This architecture leverages ABP's dynamic proxy system and event bus to provide seamless caching without modifying your business logic. |
|||
|
|||
## Prerequisites |
|||
|
|||
Before implementing automatic caching, ensure you have: |
|||
|
|||
- ABP Framework 10.0 or later |
|||
## Implementation |
|||
|
|||
> 📦 **Repository Structure**: The complete implementation is available in the [AbpAutoCacheDemo repository](https://github.com/salihozkara/AbpAutoCacheDemo). The AutoCache library is located in the `src/AutoCache` folder, making it easy to extract and reuse in your own projects. |
|||
|
|||
### Step - 1: Create the AutoCache Module |
|||
|
|||
First, let's create a separate module for our caching infrastructure. This makes it reusable across projects. |
|||
|
|||
### Step - 1: Create the AutoCache Module |
|||
|
|||
First, let's create a separate module for our caching infrastructure. This makes it reusable across projects. |
|||
|
|||
Create `AutoCache.csproj`: |
|||
|
|||
```xml |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.Caching.StackExchangeRedis" Version="10.0.0" /> |
|||
<PackageReference Include="Volo.Abp.Core" Version="10.0.0" /> |
|||
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="10.0.0" /> |
|||
</ItemGroup> |
|||
</Project> |
|||
``` |
|||
|
|||
Create the module class `AutoCacheModule.cs`: |
|||
|
|||
```csharp |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Volo.Abp.Caching.StackExchangeRedis; |
|||
using Volo.Abp.Domain; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
[DependsOn(typeof(AbpDddDomainModule), typeof(AbpCachingStackExchangeRedisModule))] |
|||
public class AutoCacheModule : AbpModule |
|||
{ |
|||
public override void PreConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.OnRegistered(AutoCacheRegister.RegisterInterceptorIfNeeded); // 👈 Register interceptor |
|||
} |
|||
} |
|||
``` |
|||
|
|||
This module automatically registers the cache interceptor for any class that uses the `CacheAttribute`. |
|||
|
|||
### Step - 2: Define the Cache Attribute |
|||
|
|||
The `CacheAttribute` is the core of our automatic caching system. It specifies which entities affect the cache and what scope to use. |
|||
|
|||
Create `CacheAttribute.cs`: |
|||
|
|||
```csharp |
|||
using System; |
|||
using Volo.Abp.Domain.Entities; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
[AttributeUsage(AttributeTargets.Method)] |
|||
public class CacheAttribute : Attribute |
|||
{ |
|||
/// <summary> |
|||
/// Entity types that affect this cache. When these entities change, the cache will be invalidated. |
|||
/// </summary> |
|||
public Type[] InvalidateOnEntities { get; set; } |
|||
|
|||
/// <summary> |
|||
/// Scope of the cache (Global, CurrentUser, AuthenticatedUser, or Entity) |
|||
/// </summary> |
|||
public AutoCacheScope Scope { get; set; } = AutoCacheScope.Global; |
|||
|
|||
/// <summary> |
|||
/// Absolute expiration time relative to now in milliseconds (0 = use default, -1 = disabled) |
|||
/// </summary> |
|||
public long AbsoluteExpirationRelativeToNow { get; set; } |
|||
|
|||
/// <summary> |
|||
/// Sliding expiration time in milliseconds (0 = use default, -1 = disabled) |
|||
/// </summary> |
|||
public long SlidingExpiration { get; set; } |
|||
|
|||
public bool ConsiderUow { get; set; } |
|||
|
|||
public string AdditionalCacheKey { get; set; } |
|||
|
|||
public CacheAttribute(params Type[] invalidateOnEntities) // 👈 Specify entities that trigger cache invalidation |
|||
{ |
|||
foreach (var entityType in invalidateOnEntities) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(entityType); |
|||
if (!typeof(IEntity).IsAssignableFrom(entityType)) |
|||
{ |
|||
throw new ArgumentException($"Type {entityType.FullName} must implement IEntity interface."); |
|||
} |
|||
} |
|||
InvalidateOnEntities = invalidateOnEntities; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
**Key Properties:** |
|||
|
|||
- **InvalidateOnEntities:** Array of entity types that, when modified, will clear this cache |
|||
- **Scope:** Determines cache visibility (Global, CurrentUser, AuthenticatedUser, Entity) |
|||
- **AbsoluteExpirationRelativeToNow / SlidingExpiration:** Control cache lifetime |
|||
|
|||
### Step - 3: Define Cache Scopes |
|||
|
|||
Cache scopes determine how cache entries are partitioned. Create `AutoCacheScope.cs`: |
|||
|
|||
```csharp |
|||
using System; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
[Flags] |
|||
public enum AutoCacheScope |
|||
{ |
|||
/// <summary> |
|||
/// Cache is shared globally across all users |
|||
/// </summary> |
|||
Global, |
|||
|
|||
/// <summary> |
|||
/// Cache is scoped to the current user (based on user ID) |
|||
/// </summary> |
|||
CurrentUser, |
|||
|
|||
/// <summary> |
|||
/// Cache is scoped to authenticated vs unauthenticated users |
|||
/// </summary> |
|||
AuthenticatedUser, |
|||
|
|||
/// <summary> |
|||
/// Cache is scoped to the primary key of the entity involved |
|||
/// </summary> |
|||
Entity |
|||
} |
|||
``` |
|||
|
|||
 |
|||
|
|||
**When to Use Each Scope:** |
|||
|
|||
- **Global:** For data that's the same for all users (e.g., configuration, public lists) |
|||
- **CurrentUser:** For user-specific data (e.g., user profile, user's orders) |
|||
- **AuthenticatedUser:** For data that differs between authenticated and anonymous users |
|||
- **Entity:** For data tied to a specific entity instance (e.g., book details by ID) |
|||
|
|||
### Step - 4: Implement the Cache Interceptor |
|||
|
|||
The interceptor is the heart of automatic caching. It intercepts method calls, checks the cache, and stores results. Create `AutoCacheInterceptor.cs`: |
|||
|
|||
```csharp |
|||
using System; |
|||
using System.Collections.Concurrent; |
|||
using System.Linq; |
|||
using System.Reflection; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Caching.Distributed; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.DynamicProxy; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
public class AutoCacheInterceptor : AbpInterceptor, ITransientDependency |
|||
{ |
|||
private readonly ILogger<AutoCacheInterceptor> _logger; |
|||
private readonly AutoCacheOptions _options; |
|||
private static readonly MethodInfo GetOrAddCacheAsyncMethod; |
|||
private readonly AutoCacheManager _autoCacheManager; |
|||
private static readonly ConcurrentDictionary<Type, MethodInfo> MethodCache = new(); |
|||
|
|||
static AutoCacheInterceptor() |
|||
{ |
|||
GetOrAddCacheAsyncMethod = typeof(AutoCacheInterceptor).GetMethod( |
|||
nameof(GetOrAddCacheAsync), |
|||
BindingFlags.NonPublic | BindingFlags.Instance |
|||
)!; |
|||
} |
|||
|
|||
public AutoCacheInterceptor( |
|||
ILogger<AutoCacheInterceptor> logger, |
|||
IOptions<AutoCacheOptions> options, |
|||
AutoCacheManager autoCacheManager) |
|||
{ |
|||
_logger = logger; |
|||
_autoCacheManager = autoCacheManager; |
|||
_options = options.Value; |
|||
} |
|||
|
|||
public override async Task InterceptAsync(IAbpMethodInvocation invocation) |
|||
{ |
|||
// Check if caching is enabled and method has [Cache] attribute |
|||
if(!_options.Enabled || |
|||
invocation.Method.GetCustomAttributes(typeof(CacheAttribute), true).FirstOrDefault() |
|||
is not CacheAttribute attribute) |
|||
{ |
|||
await invocation.ProceedAsync(); // 👈 No caching, proceed normally |
|||
return; |
|||
} |
|||
|
|||
var proceeded = false; |
|||
|
|||
try |
|||
{ |
|||
// Create generic method based on return type |
|||
var genericMethod = MethodCache.GetOrAdd(invocation.Method.ReturnType, t => |
|||
{ |
|||
var isGenericTask = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Task<>); |
|||
var resultType = isGenericTask ? t.GetGenericArguments()[0] : t; |
|||
return GetOrAddCacheAsyncMethod.MakeGenericMethod(resultType); |
|||
}); |
|||
|
|||
// Execute cache logic |
|||
(var result, proceeded) = await (Task<(object, bool)>)genericMethod.Invoke(this, [invocation, attribute])!; |
|||
invocation.ReturnValue = result; // 👈 Set cached or fresh result |
|||
} |
|||
catch (Exception e) |
|||
{ |
|||
_logger.LogError(e, "Error occurred while caching method {MethodName}", invocation.Method.Name); |
|||
|
|||
if(e is AutoCacheExceptionWrapper exceptionWrapper) |
|||
{ |
|||
if (_options.ThrowOnError) |
|||
{ |
|||
throw exceptionWrapper.OriginalException; |
|||
} |
|||
|
|||
_logger.LogWarning( |
|||
"Cache operation failed, falling back to method execution for {MethodName}", |
|||
invocation.Method.Name |
|||
); |
|||
} |
|||
|
|||
if (!proceeded && invocation.ReturnValue == null) |
|||
{ |
|||
await invocation.ProceedAsync(); // 👈 Fallback to actual method execution |
|||
} |
|||
} |
|||
} |
|||
|
|||
private async Task<(object?, bool)> GetOrAddCacheAsync<TResult>( |
|||
IAbpMethodInvocation invocation, |
|||
CacheAttribute attribute) |
|||
{ |
|||
var proceeded = false; |
|||
var result = await _autoCacheManager.GetOrAddAsync( |
|||
invocation.TargetObject, |
|||
Factory, |
|||
invocation.Arguments, |
|||
() => new DistributedCacheEntryOptions |
|||
{ |
|||
AbsoluteExpirationRelativeToNow = GetExpiration( |
|||
attribute.AbsoluteExpirationRelativeToNow, |
|||
_options.DefaultAbsoluteExpirationRelativeToNow), |
|||
SlidingExpiration = GetExpiration( |
|||
attribute.SlidingExpiration, |
|||
_options.DefaultSlidingExpiration) |
|||
}, |
|||
attribute.InvalidateOnEntities, |
|||
attribute.Scope, |
|||
attribute.ConsiderUow, |
|||
attribute.AdditionalCacheKey, |
|||
invocation.Method.Name); |
|||
|
|||
return (result, proceeded); |
|||
|
|||
async Task<TResult> Factory() |
|||
{ |
|||
await invocation.ProceedAsync(); // 👈 Execute actual method on cache miss |
|||
proceeded = true; |
|||
return (TResult)invocation.ReturnValue; |
|||
} |
|||
} |
|||
|
|||
private static TimeSpan? GetExpiration(long milliseconds, long defaultValue) |
|||
{ |
|||
return milliseconds switch |
|||
{ |
|||
0 => defaultValue > 0 ? TimeSpan.FromMilliseconds(defaultValue) : null, |
|||
< 0 => null, |
|||
_ => TimeSpan.FromMilliseconds(milliseconds) |
|||
}; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
The interceptor intelligently determines whether to serve cached data or execute the actual method. |
|||
|
|||
### Step - 5: Implement the Cache Manager |
|||
|
|||
The `AutoCacheManager` handles the actual cache operations. Create a simplified version: |
|||
|
|||
```csharp |
|||
using System; |
|||
using System.Runtime.CompilerServices; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Caching.Distributed; |
|||
using Microsoft.Extensions.Logging; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.DynamicProxy; |
|||
using Volo.Abp.Users; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
public class AutoCacheManager : IScopedDependency |
|||
{ |
|||
private readonly IAutoCacheKeyManager _autoCacheKeyManager; |
|||
private readonly ICurrentUser _currentUser; |
|||
private readonly ILogger<AutoCacheManager> _logger; |
|||
private readonly IAutoCacheMetrics _metrics; |
|||
private readonly AutoCacheOptions _options; |
|||
|
|||
public AutoCacheManager( |
|||
IAutoCacheKeyManager autoCacheKeyManager, |
|||
ICurrentUser currentUser, |
|||
ILogger<AutoCacheManager> logger, |
|||
IAutoCacheMetrics metrics, |
|||
IOptions<AutoCacheOptions> options) |
|||
{ |
|||
_autoCacheKeyManager = autoCacheKeyManager; |
|||
_currentUser = currentUser; |
|||
_logger = logger; |
|||
_metrics = metrics; |
|||
_options = options.Value; |
|||
} |
|||
|
|||
public async Task<TResult> GetOrAddAsync<TResult>( |
|||
object? caller, |
|||
Func<Task<TResult>> func, |
|||
object?[]? parameters = null, |
|||
Func<DistributedCacheEntryOptions>? optionsFactory = null, |
|||
Type[]? invalidateOnEntities = null, |
|||
AutoCacheScope scope = AutoCacheScope.Global, |
|||
bool considerUow = false, |
|||
string? additionalCacheKey = null, |
|||
[CallerMemberName] string methodName = "") |
|||
{ |
|||
if (!_options.Enabled) |
|||
{ |
|||
return await func(); // 👈 Caching disabled, execute directly |
|||
} |
|||
|
|||
var callerType = caller != null ? ProxyHelper.GetUnProxiedType(caller) : GetType(); |
|||
parameters ??= []; |
|||
|
|||
// Generate unique cache key based on method, parameters, and scope |
|||
var cacheKey = GenerateCacheKey<TResult>( |
|||
callerType.Name, |
|||
additionalCacheKey, |
|||
methodName, |
|||
parameters, |
|||
scope); |
|||
|
|||
var (cachedResult, exception, wasHit) = await GetOrAddCacheAsync( |
|||
cacheKey, |
|||
func, |
|||
optionsFactory, |
|||
considerUow |
|||
); |
|||
|
|||
// Record metrics |
|||
if (wasHit) |
|||
{ |
|||
_metrics.RecordHit(cacheKey); |
|||
} |
|||
else |
|||
{ |
|||
_metrics.RecordMiss(cacheKey); |
|||
} |
|||
|
|||
if (exception != null) |
|||
{ |
|||
_metrics.RecordError(cacheKey, exception); |
|||
|
|||
if (_options.ThrowOnError) |
|||
{ |
|||
throw exception; |
|||
} |
|||
} |
|||
|
|||
return cachedResult; |
|||
} |
|||
|
|||
private string GenerateCacheKey<TResult>( |
|||
string callerTypeName, |
|||
string? additionalCacheKey, |
|||
string methodName, |
|||
object?[] parameters, |
|||
AutoCacheScope scope) |
|||
{ |
|||
var keyBuilder = new StringBuilder(); |
|||
keyBuilder.Append($"{callerTypeName}:{methodName}"); |
|||
|
|||
// Add parameters to key |
|||
foreach (var param in parameters) |
|||
{ |
|||
keyBuilder.Append($":{param}"); |
|||
} |
|||
|
|||
// Add scope-specific segments |
|||
if (scope.HasFlag(AutoCacheScope.CurrentUser) && _currentUser.Id.HasValue) |
|||
{ |
|||
keyBuilder.Append($":user:{_currentUser.Id}"); // 👈 User-specific cache key |
|||
} |
|||
|
|||
if (scope.HasFlag(AutoCacheScope.AuthenticatedUser)) |
|||
{ |
|||
keyBuilder.Append($":auth:{_currentUser.IsAuthenticated}"); |
|||
} |
|||
|
|||
if (!string.IsNullOrEmpty(additionalCacheKey)) |
|||
{ |
|||
keyBuilder.Append($":{additionalCacheKey}"); |
|||
} |
|||
|
|||
return keyBuilder.ToString(); |
|||
} |
|||
|
|||
// Additional methods for cache retrieval and storage... |
|||
} |
|||
``` |
|||
|
|||
The manager generates unique cache keys based on method signatures, parameters, and scope settings. |
|||
|
|||
### Step - 6: Implement Cache Invalidation |
|||
|
|||
When entities change, related caches must be cleared. Create `AutoCacheInvalidationHandler.cs`: |
|||
|
|||
```csharp |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Logging; |
|||
using Volo.Abp.Domain.Entities; |
|||
using Volo.Abp.Domain.Entities.Events; |
|||
using Volo.Abp.EventBus; |
|||
using Volo.Abp.Uow; |
|||
|
|||
namespace AutoCache; |
|||
|
|||
public class AutoCacheInvalidationHandler<TEntity> : |
|||
ILocalEventHandler<EntityChangedEventData<TEntity>> |
|||
where TEntity : class, IEntity |
|||
{ |
|||
private readonly IAutoCacheKeyManager _autoCacheKeyManager; |
|||
private readonly ILogger<AutoCacheInvalidationHandler<TEntity>> _logger; |
|||
private readonly IUnitOfWorkManager _unitOfWorkManager; |
|||
|
|||
public AutoCacheInvalidationHandler( |
|||
IAutoCacheKeyManager autoCacheKeyManager, |
|||
ILogger<AutoCacheInvalidationHandler<TEntity>> logger, |
|||
IUnitOfWorkManager unitOfWorkManager) |
|||
{ |
|||
_autoCacheKeyManager = autoCacheKeyManager; |
|||
_logger = logger; |
|||
_unitOfWorkManager = unitOfWorkManager; |
|||
} |
|||
|
|||
public async Task HandleEventAsync(EntityChangedEventData<TEntity> eventData) |
|||
{ |
|||
try |
|||
{ |
|||
var entityType = typeof(TEntity); |
|||
var context = new RemoveCacheKeyContext |
|||
{ |
|||
Keys = eventData.Entity.GetKeys()! |
|||
}; |
|||
|
|||
// Clear cache after unit of work completes |
|||
if(_unitOfWorkManager.Current != null) |
|||
{ |
|||
_unitOfWorkManager.Current.OnCompleted(async () => |
|||
{ |
|||
await _autoCacheKeyManager.RemoveCacheAndCacheKeys(entityType, context); // 👈 Invalidate cache |
|||
}); |
|||
} |
|||
else |
|||
{ |
|||
await _autoCacheKeyManager.RemoveCacheAndCacheKeys(entityType, context); |
|||
} |
|||
} |
|||
catch (Exception e) |
|||
{ |
|||
_logger.LogError( |
|||
e, |
|||
"Error occurred while clearing cache for entity type {EntityType}", |
|||
typeof(TEntity).FullName |
|||
); |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
 |
|||
|
|||
This handler listens to entity change events and automatically clears related caches. The invalidation happens after the unit of work completes to ensure data consistency. |
|||
|
|||
### Step - 7: Configure AutoCache in Your Application |
|||
|
|||
Add the `AutoCacheModule` to your application module dependencies: |
|||
|
|||
```csharp |
|||
[DependsOn( |
|||
typeof(AutoCacheModule), // 👈 Add AutoCache module |
|||
typeof(AbpCachingStackExchangeRedisModule), |
|||
// ... other modules |
|||
)] |
|||
public class YourApplicationModule : AbpModule |
|||
{ |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
Configure<AutoCacheOptions>(options => |
|||
{ |
|||
options.Enabled = true; // 👈 Enable caching |
|||
options.DefaultAbsoluteExpirationRelativeToNow = 3600000; // 1 hour |
|||
options.DefaultSlidingExpiration = 600000; // 10 minutes |
|||
options.ThrowOnError = false; // Fallback to method execution on cache errors |
|||
}); |
|||
|
|||
// Configure Redis (if using distributed cache) |
|||
Configure<AbpDistributedCacheOptions>(options => |
|||
{ |
|||
options.KeyPrefix = "YourApp:"; |
|||
}); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Step - 8: Use Automatic Caching in Application Services |
|||
|
|||
Now comes the easy part - using automatic caching! Simply add the `[Cache]` attribute to your methods: |
|||
|
|||
```csharp |
|||
using AutoCache; |
|||
|
|||
[Authorize(AutoCacheDemoPermissions.Books.Default)] |
|||
public class BookAppService : ApplicationService, IBookAppService |
|||
{ |
|||
private readonly IRepository<Book, Guid> _repository; |
|||
private readonly AutoCacheManager _autoCacheManager; |
|||
|
|||
public BookAppService(IRepository<Book, Guid> repository, AutoCacheManager autoCacheManager) |
|||
{ |
|||
_repository = repository; |
|||
_autoCacheManager = autoCacheManager; |
|||
} |
|||
|
|||
// Cache this method, invalidate when Book entity changes |
|||
[Cache(typeof(Book), Scope = AutoCacheScope.Global)] |
|||
public virtual async Task<BookDto> GetAsync(Guid id) |
|||
{ |
|||
// You can also use AutoCacheManager directly for nested caching |
|||
var book = await _autoCacheManager.GetOrAddAsync( |
|||
this, |
|||
async () => await _repository.GetAsync(id), |
|||
[id], // 👈 Method parameters |
|||
invalidateOnEntities: [typeof(Book)], |
|||
scope: AutoCacheScope.Entity); |
|||
|
|||
return ObjectMapper.Map<Book, BookDto>(book!); |
|||
} |
|||
|
|||
// Cache book list, invalidate when any Book changes |
|||
[Cache(typeof(Book))] |
|||
public virtual async Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input) |
|||
{ |
|||
var queryable = await _repository.GetQueryableAsync(); |
|||
var query = queryable |
|||
.OrderBy(input.Sorting.IsNullOrWhiteSpace() ? "Name" : input.Sorting) |
|||
.Skip(input.SkipCount) |
|||
.Take(input.MaxResultCount); |
|||
|
|||
var books = await AsyncExecuter.ToListAsync(query); |
|||
var totalCount = await AsyncExecuter.CountAsync(queryable); |
|||
|
|||
return new PagedResultDto<BookDto>( |
|||
totalCount, |
|||
ObjectMapper.Map<List<Book>, List<BookDto>>(books) |
|||
); |
|||
} |
|||
|
|||
// No caching on write operations |
|||
[Authorize(AutoCacheDemoPermissions.Books.Create)] |
|||
public async Task<BookDto> CreateAsync(CreateUpdateBookDto input) |
|||
{ |
|||
var book = ObjectMapper.Map<CreateUpdateBookDto, Book>(input); |
|||
await _repository.InsertAsync(book); // 👈 This will trigger cache invalidation |
|||
return ObjectMapper.Map<Book, BookDto>(book); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
**What Happens Here:** |
|||
|
|||
1. When `GetAsync` is called, the interceptor checks the cache |
|||
2. On cache miss, the actual method executes and the result is cached |
|||
3. When `CreateAsync` inserts a `Book`, the invalidation handler clears all caches related to `Book` |
|||
4. Next call to `GetAsync` will fetch fresh data |
|||
|
|||
## Advanced Features |
|||
|
|||
### User-Specific Caching |
|||
|
|||
For user-specific data, use `AutoCacheScope.CurrentUser`: |
|||
|
|||
```csharp |
|||
[Cache(typeof(Order), Scope = AutoCacheScope.CurrentUser)] |
|||
public virtual async Task<List<OrderDto>> GetMyOrdersAsync() |
|||
{ |
|||
var orders = await _orderRepository.GetListAsync(x => x.UserId == CurrentUser.Id); |
|||
return ObjectMapper.Map<List<Order>, List<OrderDto>>(orders); |
|||
} |
|||
``` |
|||
|
|||
Each user gets their own cache entry, automatically invalidated when their orders change. |
|||
|
|||
### Custom Cache Keys |
|||
|
|||
For fine-grained control, add custom cache key segments: |
|||
|
|||
```csharp |
|||
[Cache( |
|||
typeof(Product), |
|||
Scope = AutoCacheScope.Global, |
|||
AdditionalCacheKey = "featured" |
|||
)] |
|||
public virtual async Task<List<ProductDto>> GetFeaturedProductsAsync() |
|||
{ |
|||
// Only featured products are cached separately |
|||
return await GetProductsByCategoryAsync("Featured"); |
|||
} |
|||
``` |
|||
|
|||
### Performance Metrics |
|||
|
|||
Monitor cache performance using `IAutoCacheMetrics`: |
|||
|
|||
```csharp |
|||
public class CacheMonitoringService : ITransientDependency |
|||
{ |
|||
private readonly IAutoCacheMetrics _metrics; |
|||
|
|||
public CacheMonitoringService(IAutoCacheMetrics metrics) |
|||
{ |
|||
_metrics = metrics; |
|||
} |
|||
|
|||
public AutoCacheStatistics GetStatistics() |
|||
{ |
|||
return _metrics.GetStatistics(); // 👈 Get hit rate, miss count, error count |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Testing the Application |
|||
|
|||
### 1. Run the Application |
|||
|
|||
```bash |
|||
abp new BookStore -u mvc -d ef |
|||
cd BookStore |
|||
dotnet run --project src/BookStore.Web |
|||
``` |
|||
|
|||
### 2. Test Cache Behavior |
|||
|
|||
Create a simple test to verify caching: |
|||
|
|||
```csharp |
|||
[Fact] |
|||
public async Task Should_Cache_Book_Results() |
|||
{ |
|||
// First call - cache miss |
|||
var book1 = await _bookAppService.GetAsync(testBookId); |
|||
|
|||
// Second call - cache hit (should be faster) |
|||
var book2 = await _bookAppService.GetAsync(testBookId); |
|||
|
|||
book1.Name.ShouldBe(book2.Name); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Invalidate_Cache_On_Update() |
|||
{ |
|||
// Cache the book |
|||
var book1 = await _bookAppService.GetAsync(testBookId); |
|||
|
|||
// Update the book |
|||
await _bookAppService.UpdateAsync(testBookId, new CreateUpdateBookDto |
|||
{ |
|||
Name = "Updated Name" |
|||
}); |
|||
|
|||
// Fetch again - should get updated data (cache was invalidated) |
|||
var book2 = await _bookAppService.GetAsync(testBookId); |
|||
|
|||
book2.Name.ShouldBe("Updated Name"); |
|||
} |
|||
``` |
|||
|
|||
### 3. Monitor Cache Performance |
|||
|
|||
Check your application logs for cache metrics: |
|||
|
|||
``` |
|||
[INF] Cache Hit: BookAppService:GetAsync:book-id-123 (Response Time: 5ms) |
|||
[INF] Cache Miss: BookAppService:GetListAsync (Response Time: 156ms) |
|||
[INF] Cache Invalidation: Book entity changed, cleared 3 cache entries |
|||
``` |
|||
|
|||
## Key Takeaways |
|||
|
|||
✅ **Automatic caching reduces boilerplate code** - Just add `[Cache]` attribute to methods instead of manual cache management |
|||
|
|||
✅ **Smart invalidation keeps data fresh** - Entity changes automatically clear related caches without manual intervention |
|||
|
|||
✅ **Multiple scoping options** - Support for global, user-specific, authenticated, and entity-level caching strategies |
|||
|
|||
✅ **Built-in fallback handling** - Gracefully falls back to method execution if caching fails |
|||
|
|||
✅ **Performance monitoring** - Track cache hits, misses, and errors for optimization |
|||
|
|||
## Conclusion |
|||
|
|||
Automatic method-level caching dramatically simplifies performance optimization in ABP Framework applications. By using attributes and interceptors, you can add sophisticated caching behavior without cluttering your business logic with cache management code. |
|||
|
|||
The system we've built provides intelligent cache invalidation, multiple scoping strategies, and built-in monitoring - all while maintaining clean, readable code. Whether you're building a small application or an enterprise system, this approach scales elegantly and integrates seamlessly with ABP's architecture. |
|||
|
|||
Ready to implement this in your project? The complete working implementation is available in the [AbpAutoCacheDemo repository](https://github.com/salihozkara/AbpAutoCacheDemo). You can clone the repository, explore the code, and even extract the `src/AutoCache` folder to use it as a standalone library in your own ABP applications. The [main implementation commit](https://github.com/salihozkara/AbpAutoCacheDemo/commit/946df1fc07de6eddd26eb14013a09968cd59329b) shows all the components working together, including interceptor registration, cache key management, and automatic invalidation handlers.r you're building a small application or an enterprise system, this approach scales elegantly and integrates seamlessly with ABP's architecture. |
|||
|
|||
Ready to implement this in your project? Check out the complete working example in the repository linked below, and start improving your application's performance today! |
|||
|
|||
### See Also |
|||
|
|||
- [ABP Caching Documentation](https://abp.io/docs/latest/framework/fundamentals/caching) |
|||
- [Interceptors in ABP](https://abp.io/docs/latest/framework/infrastructure/interceptors) |
|||
- [Event Bus Documentation](https://abp.io/docs/latest/framework/infrastructure/event-bus) |
|||
- [Sample Project on GitHub](https://github.com/salihozkara/AbpAutoCacheDemo) |
|||
|
|||
--- |
|||
|
|||
## References |
|||
|
|||
- [ABP Framework Documentation](https://docs.abp.io) |
|||
- [Redis Distributed Caching](https://redis.io/docs/) |
|||
- [Aspect-Oriented Programming Patterns](https://en.wikipedia.org/wiki/Aspect-oriented_programming) |
|||
@ -0,0 +1 @@ |
|||
Learn how to implement automatic method-level caching in ABP Framework using attributes and interceptors. This comprehensive guide covers building a reusable cache infrastructure with attribute-based caching, intelligent cache invalidation when entities change, support for multiple cache scopes (Global, CurrentUser, AuthenticatedUser, and Entity), seamless integration with ABP's dynamic proxy system and event bus, and built-in performance metrics for monitoring cache effectiveness in production applications. |
|||
@ -0,0 +1,280 @@ |
|||
```json |
|||
//[doc-seo] |
|||
{ |
|||
"Description": "Learn how to configure Server-Side Rendering (SSR) for your Angular application in the ABP Framework to improve performance and SEO." |
|||
} |
|||
``` |
|||
|
|||
# SSR Configuration |
|||
|
|||
[Server-Side Rendering (SSR)](https://angular.io/guide/ssr) is a process that involves rendering pages on the server, resulting in initial HTML content that contains the page state. This allows the browser to show the page to the user immediately, before the JavaScript bundles are downloaded and executed. |
|||
|
|||
SSR improves the **performance** (First Contentful Paint) and **SEO** (Search Engine Optimization) of your application. |
|||
|
|||
## 1. Install ABP Angular SSR |
|||
|
|||
The ABP Framework provides a schematic to easily add SSR support to your Angular application. |
|||
|
|||
Run the following command in the root folder of your Angular application: |
|||
|
|||
```shell |
|||
yarn ng generate @abp/ng.schematics:ssr-add |
|||
``` |
|||
|
|||
Alternatively, you can specify the project name if you have a multi-project workspace: |
|||
|
|||
```shell |
|||
yarn ng generate @abp/ng.schematics:ssr-add --project MyProjectName |
|||
``` |
|||
|
|||
This command automates the setup process by installing necessary dependencies, creating server-side entry points, and updating your configuration files. |
|||
|
|||
## 2. What Changes? |
|||
|
|||
When you run the schematic, it performs the following actions: |
|||
|
|||
### 2.1. Dependencies |
|||
|
|||
It adds the following packages to your `package.json`: |
|||
|
|||
- **express**: A minimal and flexible Node.js web application framework. |
|||
- **@types/express**: Type definitions for Express. |
|||
- **openid-client**: A library for OpenID Connect (OIDC) relying party (RP) implementation, used for authentication on the server. |
|||
|
|||
```json |
|||
{ |
|||
"dependencies": { |
|||
"express": "^4.18.2", |
|||
"openid-client": "^5.6.4" |
|||
}, |
|||
"devDependencies": { |
|||
"@types/express": "^4.17.17" |
|||
} |
|||
} |
|||
``` |
|||
|
|||
**For Webpack projects only:** |
|||
- **browser-sync** (Dev dependency): Used for live reloading during development. |
|||
|
|||
### 2.2. Scripts & Configuration |
|||
|
|||
The changes depend on the builder used in your project (Application Builder or Webpack). |
|||
|
|||
#### Application Builder (esbuild) |
|||
|
|||
If your project uses the **Application Builder** (`@angular/build:application`), the schematic: |
|||
|
|||
- **Scripts**: Adds `serve:ssr:project-name` to serve the SSR application. |
|||
- **angular.json**: Updates the `build` target to enable SSR (`outputMode: 'server'`) and sets the SSR entry point. |
|||
|
|||
```json |
|||
{ |
|||
"projects": { |
|||
"MyProjectName": { |
|||
"architect": { |
|||
"build": { |
|||
"options": { |
|||
"outputPath": "dist/MyProjectName", |
|||
"outputMode": "server", |
|||
"ssr": { |
|||
"entry": "src/server.ts" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
- **tsconfig**: Updates the application's `tsconfig` to include `server.ts`. |
|||
|
|||
#### Webpack Builder |
|||
|
|||
If your project uses the **Webpack Builder** (`@angular-devkit/build-angular:browser`), the schematic: |
|||
|
|||
- **Scripts**: Adds `dev:ssr`, `serve:ssr`, `build:ssr`, and `prerender` scripts. |
|||
- **angular.json**: Adds new targets: `server`, `serve-ssr`, and `prerender`. |
|||
- **tsconfig**: Updates the server's `tsconfig` to include `server.ts`. |
|||
|
|||
### 2.3. Files |
|||
|
|||
- **server.ts**: This file is the main entry point for the server-side application. |
|||
- **Standalone Projects**: Generates a server entry point compatible with `bootstrapApplication`. |
|||
- **NgModule Projects**: Generates a server entry point compatible with `platformBrowserDynamic`. |
|||
|
|||
```typescript |
|||
import { |
|||
AngularNodeAppEngine, |
|||
createNodeRequestHandler, |
|||
isMainModule, |
|||
writeResponseToNodeResponse, |
|||
} from '@angular/ssr/node'; |
|||
import express from 'express'; |
|||
import { dirname, resolve } from 'node:path'; |
|||
import { fileURLToPath } from 'node:url'; |
|||
import { environment } from './environments/environment'; |
|||
import { ServerCookieParser } from '@abp/ng.core'; |
|||
import * as oidc from 'openid-client'; |
|||
|
|||
// ... (OIDC configuration and setup) |
|||
|
|||
const app = express(); |
|||
const angularApp = new AngularNodeAppEngine(); |
|||
|
|||
// ... (OIDC routes: /authorize, /logout, /) |
|||
|
|||
/** |
|||
* Serve static files from /browser |
|||
*/ |
|||
app.use( |
|||
express.static(browserDistFolder, { |
|||
maxAge: '1y', |
|||
index: false, |
|||
redirect: false, |
|||
}), |
|||
); |
|||
|
|||
/** |
|||
* Handle all other requests by rendering the Angular application. |
|||
*/ |
|||
app.use((req, res, next) => { |
|||
angularApp |
|||
.handle(req) |
|||
.then(response => { |
|||
if (response) { |
|||
res.cookie('ssr-init', 'true', {...secureCookie, httpOnly: false}); |
|||
return writeResponseToNodeResponse(response, res); |
|||
} else { |
|||
return next() |
|||
} |
|||
}) |
|||
.catch(next); |
|||
}); |
|||
|
|||
// ... (Start server logic) |
|||
|
|||
export const reqHandler = createNodeRequestHandler(app); |
|||
``` |
|||
- **app.routes.server.ts**: Defines server-side routes and render modes (e.g., Prerender, Server, Client). This allows fine-grained control over how each route is rendered. |
|||
|
|||
```typescript |
|||
import { RenderMode, ServerRoute } from '@angular/ssr'; |
|||
|
|||
export const serverRoutes: ServerRoute[] = [ |
|||
{ |
|||
path: '**', |
|||
renderMode: RenderMode.Server |
|||
} |
|||
]; |
|||
``` |
|||
|
|||
- **app.config.server.ts**: Merges the application configuration with server-specific providers. |
|||
|
|||
```typescript |
|||
import { mergeApplicationConfig, ApplicationConfig, provideAppInitializer, inject, PLATFORM_ID, TransferState } from '@angular/core'; |
|||
import { isPlatformServer } from '@angular/common'; |
|||
import { provideServerRendering, withRoutes } from '@angular/ssr'; |
|||
import { appConfig } from './app.config'; |
|||
import { serverRoutes } from './app.routes.server'; |
|||
import { SSR_FLAG } from '@abp/ng.core'; |
|||
|
|||
const serverConfig: ApplicationConfig = { |
|||
providers: [ |
|||
provideAppInitializer(() => { |
|||
const platformId = inject(PLATFORM_ID); |
|||
const transferState = inject<TransferState>(TransferState); |
|||
if (isPlatformServer(platformId)) { |
|||
transferState.set(SSR_FLAG, true); |
|||
} |
|||
}), |
|||
provideServerRendering(withRoutes(serverRoutes)), |
|||
], |
|||
}; |
|||
|
|||
export const config = mergeApplicationConfig(appConfig, serverConfig); |
|||
``` |
|||
- **index.html**: Removes the loading spinner (`<div id="lp-page-loader"></div>`) to prevent hydration mismatches. |
|||
|
|||
## 3. Running the Application |
|||
|
|||
After the installation is complete, you can run your application with SSR support. |
|||
|
|||
### Application Builder |
|||
|
|||
To serve the application with SSR in development: |
|||
|
|||
```shell |
|||
yarn start |
|||
# or |
|||
yarn ng serve |
|||
``` |
|||
|
|||
To serve the built application (production): |
|||
|
|||
```shell |
|||
yarn run serve:ssr:project-name |
|||
``` |
|||
|
|||
### Webpack Builder |
|||
|
|||
**Development:** |
|||
|
|||
```shell |
|||
yarn run dev:ssr |
|||
``` |
|||
|
|||
**Production:** |
|||
|
|||
```shell |
|||
yarn run build:ssr |
|||
yarn run serve:ssr |
|||
``` |
|||
|
|||
## 4. Authentication & SSR |
|||
|
|||
The schematic installs `openid-client` to handle authentication on the server side. This ensures that when a user accesses a protected route, the server can validate their session or redirect them to the login page before rendering the content. |
|||
|
|||
> Ensure your OpenID Connect configuration (in `environment.ts` or `app.config.ts`) is compatible with the server environment. |
|||
|
|||
## 5. Deployment |
|||
|
|||
To deploy your Angular SSR application to a production server, follow these steps: |
|||
|
|||
### 5.1. Build the Application |
|||
|
|||
Run the build command to generate the production artifacts: |
|||
|
|||
```shell |
|||
yarn build |
|||
# or if using Webpack builder |
|||
yarn run build:ssr |
|||
``` |
|||
|
|||
### 5.2. Prepare Artifacts |
|||
|
|||
After the build is complete, you will find the output in the `dist` folder. |
|||
For the **Application Builder**, the output structure typically looks like this: |
|||
|
|||
``` |
|||
dist/MyProjectName/ |
|||
├── browser/ # Client-side bundles |
|||
└── server/ # Server-side bundles and entry point (server.mjs) |
|||
``` |
|||
|
|||
You need to copy the entire `dist/MyProjectName` folder to your server. |
|||
|
|||
### 5.3. Run the Server |
|||
|
|||
On your server, navigate to the folder where you copied the artifacts and run the server using Node.js: |
|||
|
|||
```shell |
|||
node server/server.mjs |
|||
``` |
|||
|
|||
> [!TIP] |
|||
> It is recommended to use a process manager like [PM2](https://pm2.keymetrics.io/) to keep your application alive and handle restarts. |
|||
|
|||
```shell |
|||
pm2 start server/server.mjs --name "my-app" |
|||
``` |
|||
|
After Width: | Height: | Size: 16 KiB |
@ -0,0 +1,22 @@ |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Microsoft.Extensions.Options; |
|||
using Volo.Abp.Options; |
|||
|
|||
namespace Microsoft.Extensions.DependencyInjection; |
|||
|
|||
public static class ServiceCollectionOptionsExtensions |
|||
{ |
|||
/// <summary>
|
|||
/// You should only use this method to register options if you need to continue using the ServiceProvider to get other options in your Options configuration method.
|
|||
/// Otherwise, please use the default AddOptions method for better performance.
|
|||
/// </summary>
|
|||
/// <param name="services"></param>
|
|||
/// <typeparam name="TOptions"></typeparam>
|
|||
/// <returns></returns>
|
|||
public static OptionsBuilder<TOptions> AddAbpOptions<TOptions>(this IServiceCollection services) |
|||
where TOptions : class |
|||
{ |
|||
services.TryAddSingleton<IOptions<TOptions>, AbpUnnamedOptionsManager<TOptions>>(); |
|||
return services.AddOptions<TOptions>(); |
|||
} |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
using Microsoft.Extensions.Options; |
|||
|
|||
namespace Volo.Abp.Options; |
|||
|
|||
/// <summary>
|
|||
/// This Options manager is similar to Microsoft UnnamedOptionsManager but without the locking mechanism.
|
|||
/// Prevent deadlocks when accessing options in multiple threads.
|
|||
/// </summary>
|
|||
/// <typeparam name="TOptions"></typeparam>
|
|||
public class AbpUnnamedOptionsManager<TOptions> : IOptions<TOptions> |
|||
where TOptions : class |
|||
{ |
|||
private readonly IOptionsFactory<TOptions> _factory; |
|||
private TOptions? _value; |
|||
|
|||
public AbpUnnamedOptionsManager(IOptionsFactory<TOptions> factory) |
|||
{ |
|||
_factory = factory; |
|||
} |
|||
|
|||
public TOptions Value |
|||
{ |
|||
get |
|||
{ |
|||
if (_value is { } value) |
|||
{ |
|||
return value; |
|||
} |
|||
|
|||
_value = _factory.Create(Microsoft.Extensions.Options.Options.DefaultName); |
|||
return _value; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,6 @@ |
|||
namespace Volo.Abp.EntityFrameworkCore; |
|||
|
|||
public class AbpSqliteOptions |
|||
{ |
|||
public int? BusyTimeout { get; set; } |
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.EntityFrameworkCore.Diagnostics; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.Interceptors; |
|||
|
|||
/// <summary>
|
|||
/// https://github.com/dotnet/efcore/issues/29514
|
|||
/// </summary>
|
|||
public class SqliteBusyTimeoutSaveChangesInterceptor : SaveChangesInterceptor |
|||
{ |
|||
private readonly string _pragmaCommand; |
|||
|
|||
public SqliteBusyTimeoutSaveChangesInterceptor(int timeoutMilliseconds) |
|||
{ |
|||
_pragmaCommand = $"PRAGMA busy_timeout={timeoutMilliseconds};"; |
|||
} |
|||
|
|||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result) |
|||
{ |
|||
if (eventData.Context != null) |
|||
{ |
|||
eventData.Context.Database.ExecuteSqlRaw(_pragmaCommand); |
|||
} |
|||
|
|||
return result; |
|||
} |
|||
|
|||
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default) |
|||
{ |
|||
if (eventData.Context != null) |
|||
{ |
|||
await eventData.Context.Database.ExecuteSqlRawAsync(_pragmaCommand, cancellationToken: cancellationToken); |
|||
} |
|||
|
|||
return await base.SavingChangesAsync(eventData, result, cancellationToken); |
|||
} |
|||
} |
|||