ABPフレームワークの主要機能とサービスの実践

現在ユーザー情報の取得

認証が必要な機能では現在ユーザー情報の取得が不可欠です。ABPはICurrentUserサービスを提供し、ASP.NET Coreと完全統合されています。

using Volo.Abp.Users;
using Volo.Abp.DependencyInjection;

namespace ServiceModule
{
    public class UserDataService : ITransientDependency
    {
        private readonly ICurrentUser _currentUser;
        
        public UserDataService(ICurrentUser currentUser)
        {
            _currentUser = currentUser;
        }

        public void ProcessUserData()
        {
            Guid? id = _currentUser.Id;
            string loginId = _currentUser.UserName;
            string mailAddress = _currentUser.Email;
        }
    }
}

ICurrentUserプロパティ

  • IsAuthenticated: 認証状態を判定
  • Id: ユーザー一意識別子
  • TenantId: マルチテナント対応のテナントID
  • Roles: ユーザーに割り当てられたロール

カスタムクレームの実装

public class CustomClaimContributor : IAbpClaimsPrincipalContributor, ITransientDependency
{
    public async Task ContributeAsync(AbpClaimsPrincipalContributorContext context)
    {
        var identity = context.ClaimsPrincipal.Identities.FirstOrDefault();
        var userId = identity?.FindUserId();
        
        if (userId.HasValue)
        {
            var customService = context.ServiceProvider.GetRequiredService<ICustomService>();
            var customValue = await customService.FetchCustomDataAsync(userId.Value);
            
            if (customValue != null)
            {
                identity.AddClaim(new Claim("CustomAttribute", customValue));
            }
        }
    }
}

データフィルタリングシステム

ABPはグローバルクエリフィルタを自動化し、ソフト削除やマルチテナンシーを実装します。

ソフト削除フィルタ

public class Product : AggregateRoot, ISoftDelete
{
    public bool IsDeleted { get; set; }
}

フィルタ無効化

public class ProductService : ITransientDependency
{
    private readonly IRepository<Product> _repository;
    private readonly IDataFilter _dataFilter;

    public async Task<List<Product>> GetAllProducts()
    {
        using (_dataFilter.Disable<ISoftDelete>())
        {
            return await _repository.GetListAsync();
        }
    }
}

カスタムフィルタ実装

public interface IArchivable
{
    bool IsArchived { get; }
}

public class Product : AggregateRoot, IArchivable
{
    public bool IsArchived { get; set; }
}

監査ログ管理

ABPはリクエストとエンティティ変更を自動追跡します。

監査設定

Configure<AbpAuditingOptions>(options =>
{
    options.IsEnabledForAnonymousUsers = false;
    options.EntityHistorySelectors.AddAllEntities();
});

監査対象の制御

[DisableAuditing]
public class ReportAppService : ApplicationService
{
    [Audited]
    public async Task GenerateReportAsync() { }
}

分散キャッシュの活用

ABPはASP.NET Coreキャッシュシステムを拡張し、マルチテナンシーをサポートします。

public class ProductCacheItem
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class ProductCacheService
{
    private readonly IDistributedCache<ProductCacheItem> _cache;

    public async Task<ProductCacheItem> GetProductAsync(Guid productId)
    {
        return await _cache.GetOrAddAsync(
            productId.ToString(),
            async () => await FetchProductAsync(productId),
            () => new DistributedCacheEntryOptions
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddHours(2)
            });
    }
}

Redis連携

"Redis": {
  "Configuration": "localhost:6379"
}

UIローカライゼーション

ABPはJSONベースの軽量なローカライゼーションを提供します。

{
  "culture": "ja",
  "texts": {
    "Welcome": "ようこそ",
    "ProductList": "製品一覧"
  }
}
[LocalizationResourceName("AppResource")]
public class AppResource { }

public class LocalizationService
{
    private readonly IStringLocalizer<AppResource> _localizer;

    public string GetWelcomeMessage(string userName)
    {
        return _localizer["WelcomeMessage", userName];
    }
}

クライアント側ローカライゼーション

const text = abp.localization.localize('WelcomeMessage', 'AppResource');

タグ: ABPフレームワーク ASP.NET Core データフィルタリング 監査ログ 分散キャッシュ

7月31日 01:49 投稿