Skip to content

Microtec Packages - Quick Reference with File Catalog

Last Updated: 2026-01-11 Total Packages: 16 Total Classes: 300+ Total Services: 40+


📦 1. Microtec.Domain (Foundation)

Purpose: Foundation package with base entities, interfaces, enums, constants, and exceptions Dependencies: NONE Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
Base EntitiesEntities/
EntityBase<TKey>Entities/EntityBase.csBase entity with typed primary key
FullAuditedEntityBaseEntities/FullAuditedEntityBase.csEntity with CreatedBy, UpdatedBy, IsActive, IsDeleted
MultiTenantEntityEntities/MultiTenantEntity.csEntity with TenantId support
SoftDeleteEntity<T>Entities/SoftDeleteEntity.csSoft delete support
LookupEntityBaseEntities/LookupEntityBase.csReference data with Name/NameAr
Service MarkersInterfaces/
IScopedServiceInterfaces/IScopedService.csAuto-registration marker for scoped lifetime
ISingletonServiceInterfaces/ISingletonService.csAuto-registration marker for singleton lifetime
ITransientServiceInterfaces/ISingletonService.csAuto-registration marker for transient lifetime
Core InterfacesInterfaces/
IRepository<TEntity>Interfaces/IRepository.csGeneric repository pattern contract
IUnitOfWork<TContext>Interfaces/IUnitOfWork.csUnit of work pattern contract
ICacheServiceInterfaces/ICacheService.csRedis caching abstraction
ISecurityServiceInterfaces/ISecurityService.csCurrent user and tenant context
IMultiTenantEntityInterfaces/IMultiTenantEntity.csMulti-tenant entity marker
EnumsEnums/
ActionTypesEnums/ActionTypes.csCRUD action types (View, Add, Edit, Delete)
AppsEnums/Apps.csApplication types (ERP, Workflow, AdminPortal)
ModulesEnums/Modules.csModule identifiers (Inventory, Sales, etc.)
PaymentMethodTypeEnums/PaymentMethodType.csCash, Card, Transfer, etc.
TrackingTypeEnums/TrackingType.csSerial, Batch, None
ConstantsConstants/
CacheKeysConstants/CacheKeys.csRedis cache key constants
ClaimNamesConstants/ClaimNames.csJWT claim names
RabbitMqQueuesConstants/RabbitMqQueues.csRabbitMQ queue names
ErrorMessagesConstants/ErrorMessages.csStandard error messages
ExceptionsExceptions/
BusinessRuleExceptionExceptions/BusinessRuleException.csBusiness rule violations (400)
NotFoundExceptionExceptions/NotFoundException.csResource not found (404)
ValidationExceptionExceptions/ValidationException.csValidation errors (400)
ForbiddenAccessExceptionExceptions/ForbiddenAccessException.csAccess forbidden (403)
ExtensionsExtensions/
QueryExtensionsExtensions/QueryExtensions.csLINQ query helpers
StringExtensionsExtensions/StringExtensions.csString utility methods
DateExtensionsExtensions/DateExtensions.csDate/time utilities
EnumExtensionsExtensions/EnumExtensions.csEnum helpers
JsonExtensionsExtensions/JsonExtensions.csJSON serialization

Common Usage:

csharp
// Multi-tenant entity with audit trail
public class Invoice : FullAuditedEntityBase, IMultiTenantEntity
{
    public Guid TenantId { get; set; }
    public string InvoiceNumber { get; set; }
}

// Auto-registered service
public class InvoiceService : IInvoiceService, IScopedService { }

📦 2. Microtec.Contracts (CQRS & Events)

Purpose: CQRS patterns, integration events, DTOs, and application layer contracts Dependencies: Microtec.Domain Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
CQRS BaseCQRS/Base/
ICommand<TResult>CQRS/Base/ICommand.csCommand interface with return type
ICommandHandler<T>CQRS/Base/ICommandHandler.csCommand handler interface
IQuery<TResult>CQRS/Base/IQuery.csQuery interface with return type
IQueryHandler<T>CQRS/Base/IQueryHandler.csQuery handler interface
CQRS InterfacesCQRS/
IEventPublisherCQRS/IEventPublisher.csIntegration event publishing via MassTransit
IAppSenderCQRS/IAppSender.csSend commands to other services
Pipeline BehaviorsCQRS/Behaviours/
ValidationBehaviourCQRS/Behaviours/ValidationBehaviour.csFluentValidation pipeline behavior
WorkflowBehaviorCQRS/Behaviours/WorkflowBehavior.csWorkflow integration behavior
RequestLoggingPipelineBehaviorCQRS/Behaviours/RequestLoggingPipelineBehavior.csRequest/response logging
UnhandledExceptionBehaviourCQRS/Behaviours/UnhandledExceptionBehaviour.csException catching and logging
Message ContractsMessageContracts/
IntegrationEventMessageContracts/IntegrationEvent.csBase class for all integration events
WebhookEventMessageContracts/WebhookEvent.csBase class for webhook events
IBaseConsumer<T>MessageContracts/IBaseConsumer.csBase consumer interface
AttributesAttributes/
PolicyMapperAttributeAttributes/PolicyMapperAttribute.csAuthorization policy mapping (ActionType, Service, License)
QueueNameAttributeAttributes/QueueNameAttribute.csRabbitMQ queue name for consumers
Integration EventsEvents/IntegrationEvents/
SubdomainCreatedIntegrationEventEvents/.../SubdomainCreatedIntegrationEvent.csSubdomain creation event
ErpBranchCreatedIntegrationEventEvents/.../ErpBranchCreatedIntegrationEvent.csBranch creation event
SendNotificationEventEvents/.../SendNotificationEvent.csNotification trigger event
Response ModelsResponse/
APIResponse<T>Response/APIResponse.csStandard API response wrapper
ErrorResponseResponse/ErrorResponse.csError response model
Extension MethodsExtensions/
ApplicationExtensionsExtensions/ApplicationExtensions.csAutoRegisterServices(), AddAutoMapperProfiles()
MediatorExtensionsExtensions/MediatorExtensions.csAddMediator(), AddFluentValidation()

Common Usage:

csharp
// Command
public class CreateInvoiceCommand : ICommand<Result<Guid>>
{
    public string InvoiceNumber { get; set; }
    public decimal Amount { get; set; }
}

// Handler
public class CreateInvoiceCommandHandler : ICommandHandler<CreateInvoiceCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(CreateInvoiceCommand request, CancellationToken ct)
    {
        // Implementation
    }
}

// Integration Event
[QueueName(RabbitMqQueues.InvoiceProcessing)]
public sealed class InvoiceCreatedConsumer : IConsumer<InvoiceCreatedEvent>, IBaseConsumer<InvoiceCreatedEvent> { }

📦 3. Microtec.Persistence (Data Access)

Purpose: EF Core repositories, unit of work, audit interceptors Dependencies: Microtec.Domain, Microtec.Contracts Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
RepositoryBase/
RepositoryBase<TEntity>Base/RepositoryBase.csGeneric repository with CRUD and querying (20+ methods)
UnitOfWork<TContext>Base/UnitOfWork.csUnit of work with transaction management
InterceptorsInterceptors/
AuditInterceptorInterceptors/AuditInterceptor.csAuto-populates CreatedBy, UpdatedBy, etc.
ExtensionsExtensions/
EntityTypeBuilderExtensionsExtensions/EntityTypeBuilderExtensions.csConfigureAuditFields(), ConfigureSoftDelete(), ConfigureMultiTenancy()
ModelBuilderExtensionsExtensions/ModelBuilderExtensions.csApplyGlobalQueryFilters(), ConfigureDecimalPrecision()
ConstantsBase/
SchemaNamesBase/SchemaNames.csDatabase schema name constants (inv, sales, fin, etc.)

Common Usage:

csharp
// Repository
public class ProductRepository : RepositoryBase<Product>, IProductRepository
{
    public ProductRepository(DbContext context) : base(context) { }

    // Inherits: GetByIdAsync, GetAllAsync, AddAsync, UpdateAsync, SoftRemove, etc.
}

// EF Configuration
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products", SchemaNames.Inventory);
        builder.ConfigureAuditFields();
        builder.ConfigureSoftDelete();
        builder.ConfigureMultiTenancy();
    }
}

// Usage with Unit of Work
await using var scope = await _unitOfWork.BeginTransactionAsync();
await _repository.AddAsync(product);
await _unitOfWork.SaveChangesAsync();
await scope.CommitAsync();

📦 4. Microtec.Messaging (RabbitMQ & Redis)

Purpose: MassTransit, Redis caching, event publishing, encryption Dependencies: Microtec.Domain, Microtec.Contracts Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
ServicesServices/
CacheServiceServices/CacheService.csRedis caching (Get, Set, Remove, Exists, GetOrSet) - Singleton
ClockServiceServices/ClockService.csTime/date provider (Now, UtcNow, Today) - Singleton
EncryptionServiceServices/EncryptionService.csAES encryption/decryption - Singleton
EventPublisherServices/EventPublisher.csPublish integration events via MassTransit - Scoped
WebhookEventPublisherServices/WebhookEventPublisher.csPublish webhook events - Scoped
AppSenderServices/AppSender.csSend commands to other services - Scoped
AppRestClientServices/AppRestClient.csHTTP REST client for service-to-service calls - Transient
LanguageProviderServices/LanguageProvider.csCurrent request language and localization - Scoped
ApplicationLogger<T>Services/ApplicationLogger.csStructured logging with correlation ID - Scoped
ExtensionsExtensions/
MassTransitExtensionsExtensions/MassTransitExtensions.csConfigureMassTransit() - RabbitMQ setup
DependencyInjectionDependencyInjection.csAddRedisCacheDb(), AddMessagingServices(), AddPlatformMessaging()

Common Usage:

csharp
// Caching
var product = await _cache.GetOrSetAsync($"product:{id}", async () =>
{
    return await _repository.GetByIdAsync(id);
}, TimeSpan.FromMinutes(30));

// Event Publishing
await _eventPublisher.PublishAsync(new OrderCreatedEvent
{
    OrderId = order.Id,
    CustomerId = order.CustomerId
});

// Encryption
var encrypted = _encryption.Encrypt(sensitiveData);
var decrypted = _encryption.Decrypt(encrypted);

📦 5. Microtec.Keycloak (Authentication)

Purpose: Keycloak integration for user/realm/role/session management Dependencies: None (standalone) Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
Service InterfacesServices/
IKeycloakProviderServices/IKeycloakProvider.csMain provider aggregating all services
IUserServiceServices/User/IUserService.csUser CRUD, password, sessions (20+ methods)
IRealmServiceServices/Realm/IRealmService.csRealm creation, configuration
IRoleServiceServices/Role/IRoleService.csRole management and assignments
IGroupServiceServices/Group/IGroupService.csGroup management
IClientServiceServices/Client/IClientService.csOAuth client management
ISessionValidationServiceServices/Session/ISessionValidationService.csToken introspection, session enforcement
OptionsOptions/
KeycloakOptionsOptions/KeycloakOptions.csBaseUrl, Realm, ClientId, Username, Password
SessionValidationOptionsOptions/SessionValidationOptions.csEnforceSingleSession, EnableTokenIntrospection
ConstantsConstants/
KeycloakUserAttributesConstants/KeycloakUserAttributes.csTenantId, BranchId, CompanyId, etc.

Common Usage:

csharp
// Create user with roles
var userId = await _keycloak.CreateUserAsync(realm, new KeycloakUserDto
{
    Username = email,
    Email = email,
    Enabled = true,
    Attributes = new Dictionary<string, string[]>
    {
        { KeycloakUserAttributes.TenantId, new[] { tenantId.ToString() } }
    }
});

await _keycloak.SetUserPasswordAsync(realm, userId, password, temporary: false);
await _keycloak.AssignRoleToUserAsync(realm, userId, "admin");

📦 6. Microtec.Reporting (PDF & Excel)

Purpose: PDF/Excel generation, QR codes Dependencies: Microtec.Domain, Microtec.Contracts, Microtec.Messaging Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
ServicesGenerateReport/
ReportGenerationServiceGenerateReport/ReportGenerationService.csMain orchestrator for reports
PdfGenerateServiceGenerateReport/Pdf/PdfGenerateService.csQuestPDF document generation
ClosedXmlExportServiceGenerateReport/Excel/ClosedXmlExportService.csExcel export with ClosedXML
QRManagerQRManager.csQR code generation (Generate, GenerateBase64)
PDF ComponentsGenerateReport/Pdf/Components/
BaseDocumentGenerateReport/Pdf/BaseDocument.csBase PDF document with header/footer
HeaderTableComponents/HeaderTable.csDocument header table component
InfoCardComponents/InfoCard.csInfo card (customer, vendor)
SummaryTableComponents/SummaryTable.csSummary/totals table
ApprovalFooterComponents/ApprovalFooter.csSignature boxes
Excel AttributesGenerateReport/Excel/
ExcelHeaderAttributeExcel/ExcelHeaderAttribute.csColumn configuration (Name, NameAr, Order, Width, Format)
ExcelExportOptionsExcel/ExcelExportOptions.csExport options (SheetName, Language, AutoFitColumns)
ConfigurationGenerateReport/Pdf/Configuration/
ReportOptionsConfiguration/ReportOptions.csGlobal report configuration
ArabicMoneyHumanizerExtensionsConfiguration/ArabicMoneyHumanizerExtensions.csNumber to Arabic words

Common Usage:

csharp
// Excel Export
public class ProductDto
{
    [ExcelHeader(Name = "Code", NameAr = "الكود", Order = 1, Width = 15)]
    public string Code { get; set; }

    [ExcelHeader(Name = "Price", NameAr = "السعر", Order = 2, Format = "#,##0.00")]
    public decimal Price { get; set; }
}

var excel = await _excelService.ExportAsync(products, new ExcelExportOptions
{
    SheetName = "Products",
    Language = "ar"
});

// PDF Generation
public class InvoiceDocument : BaseDocument
{
    protected override void ComposeContent(IContainer container)
    {
        container.Column(column =>
        {
            column.Item().Component(new HeaderTable(invoice));
            column.Item().Component(new SummaryTable(totals));
        });
    }
}

var pdf = await _pdfService.GenerateAsync(new InvoiceDocument(invoice, header, options));

📦 7. Microtec.Web.Core (ASP.NET Core)

Purpose: Base controllers, JWT, middleware, localization, security services Dependencies: Microtec.Domain, Microtec.Contracts, Microtec.Messaging Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
Base ControllersBase/
BaseControllerBase/BaseController.csBase API controller with ErrorResponse, ExportResult helpers
InternalBaseControllerBase/InternalBaseController.csInternal service-to-service APIs with API key validation
MiddlewareMiddleware/
ExceptionHandlingMiddlewareMiddleware/ExceptionHandlingMiddleware.csGlobal exception handling
CorrelationIdMiddlewareMiddleware/CorrelationIdMiddleware.csCorrelation ID generation and propagation
AuthorizationMiddlewareMiddleware/AuthorizationMiddleware.csERP authorization with permission checking
ApiKeyMiddlewareMiddleware/ApiKeyMiddleware.csAPI key validation
SanitizerMiddlewareMiddleware/SanitizerMiddleware.csXSS prevention
FeatureFlagsMiddlewareMiddleware/FeatureFlagsMiddleware.csFeature flag enforcement
AutoLogMiddleWareMiddleware/AutoLogMiddleWare.csRequest/response logging
Security ServicesSecurity/Services/
SecurityServiceSecurity/Services/SecurityService.csCurrent user/tenant context (CurrentUserId, CurrentTenantId, etc.) - Scoped
ErpAuthorizationServiceSecurity/Services/ErpAuthorizationService.csPermission checking - Scoped
AuthenticationAuthentication/
JwtProviderAuthentication/JwtProvider.csJWT token generation and validation
JwtOptionsAuthentication/JwtOptions.csIssuer, Audience, SecretKey, ExpiryMinutes
LocalizationLocalization/
JsonStringLocalizerLocalization/JsonStringLocalizer.csJSON file-based localization
JsonStringLocalizerFactoryLocalization/JsonStringLocalizerFactory.csLocalizer factory
LocalizationMiddlewareLocalization/LocalizationMiddleware.csCulture detection
Extension MethodsExtensions/
WebCoreExtensionsExtensions/WebCoreExtensions.csAddWebCoreServices(), AddWebCoreServicesLite()
MiddlewareExtensionsExtensions/MiddlewareExtensions.csMiddleware registration and pipeline setup

Common Usage:

csharp
// Base Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : BaseController
{
    [HttpGet("{id}")]
    [PolicyMapper(ActionTypes.Get, "Products", Licenses.Basic)]
    public async Task<APIResponse<ProductDto>> GetProduct(Guid id)
    {
        var result = await _sender.Send(new GetProductQuery { Id = id });
        return result.IsSuccess ? APIResponse<ProductDto>.Success(result.Value) : ErrorResponse(result.Error);
    }
}

// Security Service
var order = new Order
{
    TenantId = _security.CurrentTenantId,
    CreatedBy = _security.CurrentUserId
};

📦 8. Microtec.Web.Hosting (Complete Stack)

Purpose: OpenTelemetry, Serilog, Swagger, Hangfire, complete API stack Dependencies: Microtec.Web.Core, Microtec.Messaging, Microtec.Persistence Target: .NET 8.0

Key Files & Purposes

File/TypeLocationPurpose
Extension MethodsExtensions/
HostingExtensionsExtensions/HostingExtensions.csAddSharedWeb() - Main API stack configuration
WebApplicationExtensionsExtensions/WebApplicationExtensions.csUseSharedWeb() - Middleware pipeline setup
IntegrationExtensionsExtensions/IntegrationExtensions.csAddHangFire(), LoadPrintOutFonts()
ServicesServices/
HangfireBackgroundJobServiceServices/HangfireBackgroundJobService.csIBackgroundJobService implementation - Scoped
OptionsOptionsSetup/
ApiUrlOptionsOptionsSetup/ApiUrls/ApiUrlOptions.csExternal API URL configuration
ConfigureOptionsExtensions/ConfigureOptions.csService startup configuration (EnableAuthorization, EnableCors, etc.)

Common Usage:

csharp
var builder = WebApplication.CreateBuilder(args);

// Full API stack
builder.Services.AddSharedWeb(builder.Configuration, builder.Environment, opt =>
{
    opt.EnableAuthorization = true;
    opt.EnableCorsDefaultPolicy = true;
    opt.EnableSanitizerMiddleware = true;
});

builder.Services.AddMediator(typeof(Program).Assembly);
builder.Services.ConfigureMassTransit(builder.Configuration, typeof(Program).Assembly);

var app = builder.Build();
app.UseSharedWeb(builder.Configuration);
app.Run();

// What AddSharedWeb() includes:
// - HttpContextAccessor, HttpClient
// - JWT authentication
// - Swagger with Bearer + XApiKey
// - Exception handling
// - CORS, Compression
// - Correlation ID
// - JSON localization
// - OpenTelemetry (tracing + metrics)
// - Serilog logging
// - OWASP security headers

📦 9-11. Import Packages (Data Import)

Dependencies: Import.Domain → Import.Infrastructure → Import.Integration

Microtec.Import.Domain

  • Import domain models, interfaces, enums
  • Base import entity, import status enums
  • Import validation rules

Microtec.Import.Infrastructure

  • Excel file handling with EPPlus
  • EF Core repositories for import data
  • Storage providers (Redis, Database)

Microtec.Import.Integration

  • Import strategies and orchestration
  • Validation pipeline
  • Background processing support

Common Usage:

csharp
builder.Services.AddImportInfrastructure(configuration);
builder.Services.AddImportIntegration(configuration);

📦 12-13. ZATCA Packages (Saudi E-Invoicing)

Dependencies: Zatca.Infrastructure → Zatca.Integration

Microtec.Zatca.Infrastructure

  • ZATCA database models
  • EF Core configurations
  • Device onboarding entities

Microtec.Zatca.Integration

  • ZATCA API integration
  • Invoice submission
  • Compliance certificate management
  • QR code generation (TLV format)

Common Usage:

csharp
builder.Services.AddZatcaInfrastructure(configuration);
builder.Services.AddZatcaIntegration(configuration);

🔑 Key Extension Methods Reference

Extension MethodPackagePrerequisitesPurpose
AddSharedWeb()Web.HostingKeycloak, Redis, RabbitMQFull API stack (recommended)
AddWebCoreServices()Web.CoreMediatR, MassTransit, RedisAuto-register all services
AddWebCoreServicesLite()Web.CoreNoneLightweight (excludes Messaging)
AddMediator()ContractsNoneMediatR + pipeline behaviors
ConfigureMassTransit()MessagingRabbitMQRabbitMQ messaging
AddMessagingServices()MessagingMediatR, MassTransit, RedisCache, encryption, events
AddKeycloakServices()KeycloakKeycloak serverAll Keycloak services
AddJSONLocalization()Web.CoreNoneJSON-based localization
AddHangFire()Web.HostingSQL ServerBackground job processing

🏗️ Essential Patterns

1. Multi-Tenant Entity

csharp
public class Invoice : FullAuditedEntityBase, IMultiTenantEntity
{
    public Guid TenantId { get; set; }
    public string InvoiceNumber { get; set; }
}

2. Service Auto-Registration

csharp
public class InvoiceService : IInvoiceService, IScopedService { }
// Automatically registered as Scoped - no manual registration needed

3. CQRS Command

csharp
public class CreateInvoiceCommand : ICommand<Result<Guid>>
{
    public string InvoiceNumber { get; set; }
}

public class CreateInvoiceCommandHandler : ICommandHandler<CreateInvoiceCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(CreateInvoiceCommand request, CancellationToken ct)
    {
        // Implementation
    }
}

4. Integration Event Publishing

csharp
await _eventPublisher.PublishAsync(new OrderCreatedEvent
{
    OrderId = order.Id,
    CustomerId = order.CustomerId
});

5. Integration Event Consumer

csharp
[QueueName(RabbitMqQueues.OrderProcessing)]
public sealed class OrderCreatedConsumer : IConsumer<OrderCreatedEvent>, IBaseConsumer<OrderCreatedEvent>
{
    public async Task Consume(ConsumeContext<OrderCreatedEvent> context)
    {
        // Handle event
    }
}

6. Repository with Unit of Work

csharp
await using var scope = await _unitOfWork.BeginTransactionAsync();
await _repository.AddAsync(entity);
await _unitOfWork.SaveChangesAsync();
await scope.CommitAsync();

7. Standard API Response

csharp
return new APIResponse<ProductDto>
{
    Data = product,
    Success = true,
    Message = "Product retrieved successfully"
};


🎯 Quick Decision Guide

Need full-featured API? → Use AddSharedWeb() from Microtec.Web.Hosting

Need lightweight gateway? → Use AddWebCoreServicesLite() from Microtec.Web.Core

Need CQRS pattern? → Use AddMediator() from Microtec.Contracts

Need messaging? → Use ConfigureMassTransit() from Microtec.Messaging

Need authentication? → Use AddKeycloakServices() from Microtec.Keycloak

Need PDF/Excel reports? → Use services from Microtec.Reporting

Need background jobs? → Use AddHangFire() from Microtec.Web.Hosting


For detailed implementation examples, configuration, and best practices, refer to individual package READMEs.

Internal Documentation — Microtec