Idevs.Net.CoreLib.Autofac
0.7.2
See the version list below for details.
dotnet add package Idevs.Net.CoreLib.Autofac --version 0.7.2
NuGet\Install-Package Idevs.Net.CoreLib.Autofac -Version 0.7.2
<PackageReference Include="Idevs.Net.CoreLib.Autofac" Version="0.7.2" />
<PackageVersion Include="Idevs.Net.CoreLib.Autofac" Version="0.7.2" />
<PackageReference Include="Idevs.Net.CoreLib.Autofac" />
paket add Idevs.Net.CoreLib.Autofac --version 0.7.2
#r "nuget: Idevs.Net.CoreLib.Autofac, 0.7.2"
#:package Idevs.Net.CoreLib.Autofac@0.7.2
#addin nuget:?package=Idevs.Net.CoreLib.Autofac&version=0.7.2
#tool nuget:?package=Idevs.Net.CoreLib.Autofac&version=0.7.2
Idevs.Net.CoreLib
A comprehensive extension library for the Serenity Framework that provides enhanced functionality for data export, PDF generation, UI components, and more.
Features
- 📊 Excel Export: Advanced Excel generation with formatting, themes, and aggregation support
- 📄 PDF Export: HTML-to-PDF conversion using Puppeteer Sharp
- 🎨 UI Components: Extended form controls and formatters for Serenity
- 🔄 Service Registration: Automatic dependency injection with attributes
- 📐 Bootstrap Grid: Enhanced column width controls with Bootstrap 5 support
- 🌍 Localization: Enhanced text localization extensions
Installation
Install via NuGet Package Manager:
dotnet add package Idevs.Net.CoreLib
Or via Package Manager Console:
Install-Package Idevs.Net.CoreLib
Quick Start
1. Service Registration
From 0.7.0 onward, DI registrations are emitted at compile time by the bundled Roslyn source generator. Replace the old call with the generated extension:
using Idevs.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Generated at compile time — no runtime assembly scanning.
builder.Services.AddIdevsServices();
// Your other service registrations
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Your middleware configuration
app.UseRouting();
app.MapControllers();
app.Run();
Upgrading from 0.6.x?
AddIdevsCorelibServices()is still present but marked[Obsolete]. Replace it withAddIdevsServices(). See MIGRATION.md for the full guide.
Service discovery paths
The generator supports three ways to declare a service:
- Attribute —
[Scoped],[Singleton], or[Transient]on the implementation class. - Marker interface — implement
IScopedService,ISingletonService, orITransientService(or their generic<TService>variants) on the class or a shared base class. - Registrar — implement
IIdevsServiceRegistrarfor arbitrary imperative registrations that do not fit the attribute/marker model.
Example using a marker interface on a base class (eliminates per-type attributes):
using Idevs.Repositories;
// Every derived repository is auto-registered as scoped.
public abstract class AppRepositoryBase<TRow, TKey>(ISqlConnections c)
: RepositoryBase<TRow, TKey>(c), IScopedService
{
}
1.1. Autofac Integration
Autofac support is available from the optional Idevs.Net.CoreLib.Autofac package:
dotnet add package Idevs.Net.CoreLib.Autofac
using Idevs.Extensions;
builder.UseIdevsAutofac();
1.2. Advanced Autofac Configuration
After installing Idevs.Net.CoreLib.Autofac, you can customize the Autofac container:
// With custom container configuration
builder.UseIdevsAutofac(containerBuilder =>
{
// Your custom registrations
containerBuilder.RegisterType<MyCustomService>()
.As<IMyCustomService>()
.InstancePerLifetimeScope();
});
// With additional modules
builder.UseIdevsAutofac(new MyCustomModule(), new AnotherModule());
2. Chrome Setup for PDF Export
Important: For PDF export functionality, you need to download Chrome/Chromium:
// In Program.cs Main method (before starting the application)
public static void Main(string[] args)
{
// Download Chrome if not already present
ChromeHelper.DownloadChrome();
CreateHostBuilder(args).Build().Run();
}
Usage Examples
Excel Export
public class OrderController : ServiceEndpoint
{
private readonly IIdevsExcelExporter _excelExporter;
public OrderController(IIdevsExcelExporter excelExporter)
{
_excelExporter = excelExporter;
}
[HttpPost]
public IActionResult ExportToExcel(ListRequest request)
{
var orders = GetOrders(request); // Your data retrieval logic
// Simple export
var excelBytes = _excelExporter.Export(orders, typeof(OrderColumns));
return IdevsContentResult.Create(
excelBytes,
IdevsContentType.Excel,
"orders.xlsx"
);
}
[HttpPost]
public IActionResult ExportWithHeaders(ListRequest request)
{
var orders = GetOrders(request);
var headers = new[]
{
new ReportHeader { HeaderLine = "Order Report" },
new ReportHeader { HeaderLine = $"Generated: {DateTime.Now:yyyy-MM-dd}" },
new ReportHeader { HeaderLine = "" } // Empty line
};
var excelBytes = _excelExporter.Export(orders, typeof(OrderColumns), headers);
return IdevsContentResult.Create(excelBytes, IdevsContentType.Excel, "order-report.xlsx");
}
}
PDF Export
public class ReportController : ServiceEndpoint
{
private readonly IIdevsPdfExporter _pdfExporter;
private readonly IViewPageRenderer _viewRenderer;
public ReportController(IIdevsPdfExporter pdfExporter, IViewPageRenderer viewRenderer)
{
_pdfExporter = pdfExporter;
_viewRenderer = viewRenderer;
}
[HttpPost]
public async Task<IActionResult> GenerateReport(ReportRequest request)
{
// Render HTML from Razor view
var model = GetReportData(request);
var html = await _viewRenderer.RenderViewAsync("Reports/OrderReport", model);
// Convert to PDF
var pdfBytes = await _pdfExporter.ExportByteArrayAsync(
html,
"<div style='text-align: center;'>Order Report</div>", // Header
"<div style='text-align: center;'>Page <span class='pageNumber'></span></div>" // Footer
);
return IdevsContentResult.Create(pdfBytes, IdevsContentType.Pdf, "report.pdf");
}
}
Note From version 0.3.0 onward the PDF exporter expects pre-rendered HTML. Use your preferred templating solution (e.g., Razor via
IViewPageRenderer) before callingExportByteArrayAsyncorCreateResponseAsync.
UI Components
// Enhanced column attributes
public class OrderColumns
{
[DisplayName("Order ID"), ColumnWidth(ExtraLarge = 2)]
public string OrderId { get; set; }
[DisplayName("Customer"), FullColumnWidth]
public string CustomerName { get; set; }
[DisplayName("Order Date"), DisplayDateFormat, HalfWidth]
public DateTime OrderDate { get; set; }
[DisplayName("Amount"), DisplayNumberFormat("n2")]
public decimal Amount { get; set; }
[DisplayName("Status"), CheckboxFormatter(TrueText = "Completed", FalseText = "Pending")]
public bool IsCompleted { get; set; }
}
Service Registration with Attributes
Idevs.Net.CoreLib supports standard attributes for service registration:
Standard Attributes
// Basic usage - auto-discovers I{ClassName} interface
[Scoped]
public class OrderService : IOrderService
{
// Scoped service implementation
}
// Explicit service type specification
[Singleton(ServiceType = typeof(ICacheService))]
public class CacheService : ICacheService, IDisposable
{
// Singleton service with explicit interface
}
// Named registrations (Autofac only)
[Transient(ServiceKey = "smtp")]
public class EmailService : IEmailService
{
// SMTP email implementation
}
Legacy Attributes (Backward Compatibility)
The legacy [ScopedRegistration], [SingletonRegiatration], and [TransientRegistration]
attributes are still supported but obsolete. Prefer [Scoped], [Singleton], and [Transient]
for new code.
Advanced Features
// Named registrations (Autofac only)
[Transient(ServiceKey = "smtp")]
public class SmtpEmailService : IEmailService
{
// SMTP email implementation
}
[Transient(ServiceKey = "sendgrid")]
public class SendGridEmailService : IEmailService
{
// SendGrid email implementation
}
// Self-registration without interface
[Scoped(AllowSelfRegistration = true)]
public class UtilityService
{
public void DoWork() { }
}
Attribute Comparison
| Feature | Legacy Attributes | Standard Attributes |
|---|---|---|
| Interface Discovery | I{ClassName} only |
I{ClassName} + any interface + self-registration |
| Service Keys | Not supported | Supported (Autofac only) |
| Explicit Service Type | Not supported | Supported |
| Self-registration | Not supported | Supported |
| Status | Obsolete | Recommended |
Static Service Resolution
Prefer constructor dependency injection for new code. StaticServiceLocator is still supported, but it should be treated as a last-resort compatibility bridge for static methods or legacy code paths that cannot receive dependencies through DI.
// Initialize in your Program.cs only if static or legacy code needs it
var app = builder.Build();
app.UseIdevsStaticServiceLocator();
// Use in static methods or legacy code
public static class LegacyHelper
{
public static void ProcessData()
{
// Resolve services statically
var excelExporter = StaticServiceLocator.Resolve<IIdevsExcelExporter>();
var pdfExporter = StaticServiceLocator.Resolve<IIdevsPdfExporter>();
// Use try resolve for optional services
var optionalService = StaticServiceLocator.TryResolve<IOptionalService>();
if (optionalService != null)
{
// Use the service
}
// Use scoped resolution for per-request services
using var scope = StaticServiceLocator.CreateScope();
var scopedService = scope.ServiceProvider.GetService<IScopedService>();
}
public static void ProcessDataWithCaching()
{
// Cache only services that are registered as singletons
var cachedService = StaticServiceLocator.ResolveSingleton<IMySingletonService>();
}
}
Important: Do not use StaticServiceLocator from normal application services. Static resolution hides dependencies and can make service lifetime problems harder to diagnose.
Configuration Options
Excel Export Customization
// Custom theme
var request = new IdevsExportRequest
{
TableTheme = TableTheme.TableStyleMedium15,
CompanyName = "My Company",
ReportName = "Sales Report",
PageSize = new PageSize(PageSizes.A4, PageOrientations.Landscape)
};
PDF Export Options
// Custom page settings in your CSS
@page {
size: A4;
margin: 1in;
}
// Or use PuppeteerSharp options directly
var pdfOptions = new PdfOptions
{
Format = PaperFormat.A4,
MarginOptions = new MarginOptions
{
Top = "1in",
Right = "1in",
Bottom = "1in",
Left = "1in"
},
PreferCSSPageSize = true
};
Troubleshooting
PDF Export Issues
Problem: PDF generation fails with "Chrome not found" error Solution: Ensure Chrome is downloaded:
// Check if Chrome is available
if (!ChromeHelper.IsChromeDownloaded())
{
ChromeHelper.DownloadChrome();
}
Problem: PDF export hangs or times out Solution: Ensure your HTML doesn't have external dependencies that can't be loaded:
<style>
/* Your styles here */
</style>
Excel Export Issues
Problem: Column formatting not applied Solution: Use proper format attributes:
[DisplayNumberFormat("#,##0.00")] // For numbers
[DisplayDateFormat] // For dates (dd/MM/yyyy)
[DisplayPercentage] // For percentages
Problem: Large datasets cause memory issues Solution: Process data in chunks or use streaming:
// Process in smaller batches
const int batchSize = 10000;
for (int i = 0; i < totalRecords; i += batchSize)
{
var batch = GetDataBatch(i, batchSize);
// Process batch
}
Migration Guide
Upgrade notes for every version live in MIGRATION.md. Direct links for the most-recent transitions:
- v0.7.1 → v0.7.2 — RepositoryBase Criteria-Based Update/Delete + TryFirst Alias
- v0.6.x → v0.7.0 — Source-Generator DI Registration
- v0.5.0 → v0.6.0 — RepositoryBase Redesign
- v0.3.x → v0.5.0 — Package Layout & DI Changes
- v0.1.x → v0.2.0 — Autofac Integration
- v0.0.x → v0.1.x — Service Registration & Chrome Setup
Repositories
Idevs.Net.CoreLib ships a focused class hierarchy for data access:
SqlServiceBase— base for services that need raw SQL access without being a typed-row repository. ProvidesISqlConnections, lazyDialect,SqlQuery()/SqlInsert(t)/SqlUpdate(t)/SqlDelete(t)factories, and a uniformExecuteAsync<T>template that manages connection lifetime and composes with an optionalUnitOfWork.RepositoryBase<TRow>— typed read/list/getby/create on a SerenityIRow. Methods:- Reads:
TryFirstAsync(returnsTRow?),ListAsync,GetByAsync<TValue>. - Writes:
CreateAsync,UpdateAsync(Action<SqlUpdate>, ExpectedRows)(criteria-based partial update; defaults toExpectedRows.One),UpdateManyAsync(batch alias),DeleteAsync(Action<SqlDelete>, ExpectedRows),DeleteManyAsync. [Obsolete]sync wrappers for migration.FirstAsyncis[Obsolete]since 0.7.2 — useTryFirstAsyncinstead (same behavior, name matches Serenity'sConnection.TryFirst).
- Reads:
RepositoryBase<TRow, TKey>— adds Id-keyed CRUD onIIdRow:GetByIdAsync,GetByIdsAsync,UpdateAsync(TRow row),DeleteByIdAsync. Inherits all the criteria-based methods above; theUpdateAsync(TRow)andUpdateAsync(Action<SqlUpdate>, ...)overloads coexist by signature.
Connection key is configurable via the virtual ConnectionKey property or
the [ConnectionKey("Warehouse")] attribute.
Criteria-based update example
// Throws if zero or more than one row matches (default ExpectedRows.One).
await mappingLotRepo.UpdateAsync(u => u
.Set(cFld.McApproveQty, qty)
.Where(cFld.DocNo == docno && cFld.ProductId == productId),
uow: uow, ct: ct);
// Batch update (any number of rows accepted).
await mappingLotRepo.UpdateManyAsync(u => u
.Set(cFld.Status, "Cancelled")
.Where(cFld.DocNo == docno),
uow, ct);
For caching, see Idevs.Caching.TwoLevelCacheExtensions — async wrappers
around Serenity ITwoLevelCache.
Migrating to 0.7.2: see MIGRATION.md. Migrating from 0.5.0: see MIGRATION.md.
Cloud Upload Storage
Idevs.Net.CoreLib can replace Serenity upload storage with S3-compatible object storage.
using Idevs.Extensions;
builder.Services.AddCloudUploadStorage(builder.Configuration);
builder.Services.AddUploadStorage();
AWS S3 configuration:
{
"CloudUploadStorage": {
"Provider": "AWS",
"BucketName": "my-bucket/uploads",
"Region": "ap-southeast-1",
"KeyPrefix": "tenant-a"
}
}
Cloudflare R2 configuration:
{
"CloudUploadStorage": {
"Provider": "CloudflareR2",
"BucketName": "my-bucket",
"CloudflareAccountId": "account-id",
"AccessKey": "access-key",
"SecretKey": "secret-key"
}
}
Set "Provider": "Local" to keep Serenity's default local upload storage.
Log Manager
LogManager provides a provider-neutral bridge for code paths that cannot receive ILogger<T> through dependency injection.
using Idevs.Logging;
using Microsoft.Extensions.Logging;
LogManager.SetLoggerFactory(app.Services.GetRequiredService<ILoggerFactory>());
var logger = LogManager.GetLogger<Program>();
Serilog Integration
Serilog support is available from the optional Idevs.Net.CoreLib.Serilog package.
dotnet add package Idevs.Net.CoreLib.Serilog
using Idevs.Extensions;
app.UseIdevsSerilogLogManager();
The core package continues to use Microsoft.Extensions.Logging abstractions.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Authors
- @klomkling - Sarawut Phaekuntod
Changelog
See CHANGELOG.md for a detailed history of changes.
Made with ❤️ for the Serenity Framework community
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Autofac (>= 8.4.0)
- Autofac.Extensions.DependencyInjection (>= 10.0.0)
- Autofac.Extras.AttributeMetadata (>= 6.0.0)
- AWSSDK.S3 (>= 4.0.14)
- ClosedXML (>= 0.105.0)
- FastMember (>= 1.5.0)
- Handlebars.Net (>= 2.1.6)
- Idevs.Net.CoreLib (>= 0.7.2)
- Microsoft.Data.SqlClient (>= 6.1.1)
- PuppeteerSharp (>= 20.2.2)
- Serenity.Net.Services (>= 10.3.1)
-
net8.0
- Autofac (>= 8.4.0)
- Autofac.Extensions.DependencyInjection (>= 10.0.0)
- Autofac.Extras.AttributeMetadata (>= 6.0.0)
- AWSSDK.S3 (>= 4.0.14)
- ClosedXML (>= 0.105.0)
- FastMember (>= 1.5.0)
- Handlebars.Net (>= 2.1.6)
- Idevs.Net.CoreLib (>= 0.7.2)
- Microsoft.Data.SqlClient (>= 6.1.1)
- PuppeteerSharp (>= 20.2.2)
- Serenity.Net.Services (>= 8.8.9)
- SixLabors.ImageSharp (>= 2.1.12)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.