API Reference

A concise reference for NBatch’s public types and interfaces.


Package: NBatch

Job

A configured batch job containing one or more steps executed in sequence.

Method Returns Description
CreateBuilder(string jobName) JobBuilder Creates a new job builder (static)
RunAsync(CancellationToken) Task<JobResult> Executes all steps in order

JobBuilder

Fluent builder for configuring and creating a Job.

Method Returns Description
WithLogger(ILogger logger) JobBuilder Sets the logger for diagnostics
WithListener(IJobListener listener) JobBuilder Registers a job-level listener
WithDefaultChunkSize(int) JobBuilder Chunk size for steps that don’t set their own
WithDefaultSkipPolicy(SkipPolicy) JobBuilder Skip policy for steps that don’t set their own
WithDefaultRetryPolicy(RetryPolicy) JobBuilder Retry policy for steps that don’t set their own
AddStep(string name, Func<..., IStepBuilderFinal> configure) JobBuilder Adds a named step
Build() Job Creates the configured job (throws InvalidOperationException when no steps are registered)

Note: UseJobStore() is an extension method provided by the NBatch.EntityFrameworkCore package. See below.


Step Builder (Fluent Chain)

The AddStep delegate receives a builder that flows through these stages:

Stage 1: IStepBuilderReadFrom

Method Returns Description
ReadFrom<T>(IReader<T>) IStepBuilderProcess<T> Sets the reader
ReadFrom<TReader, TItem>() IStepBuilderProcess<TItem> Reader resolved from DI (AddNBatch jobs only)
Execute(ITasklet) ITaskletStepBuilder Creates a tasklet step
Execute<TTasklet>() ITaskletStepBuilder Tasklet resolved from DI (AddNBatch jobs only)
Execute(Func<Task>) ITaskletStepBuilder Creates a tasklet from an async lambda
Execute(Func<CancellationToken, Task>) ITaskletStepBuilder Creates a tasklet with cancellation
Execute(Action) ITaskletStepBuilder Creates a tasklet from a synchronous action

Stage 2: IStepBuilderProcess<TInput>

Method Returns Description
ProcessWith<TOutput>(IProcessor<TIn, TOut>) IStepBuilderWriteTo<TOutput> Sets the processor (interface)
ProcessWith<TOutput>(Func<TIn, TOut>) IStepBuilderWriteTo<TOutput> Synchronous lambda processor
ProcessWith<TOutput>(Func<TIn, CancellationToken, Task<TOut>>) IStepBuilderWriteTo<TOutput> Async lambda processor
ProcessWith<TProcessor, TOutput>() IStepBuilderWriteTo<TOutput> Processor resolved from DI (AddNBatch jobs only)
WriteTo(IWriter<TInput>) IStepBuilderOptions Skips processing, goes to writer
WriteTo(Func<IEnumerable<TInput>, Task>) IStepBuilderOptions Lambda writer, no processor
WriteTo(Func<IEnumerable<TInput>, CancellationToken, Task>) IStepBuilderOptions Lambda writer with cancellation
WriteTo<TWriter>() IStepBuilderOptions Writer resolved from DI (AddNBatch jobs only)

Stage 3: IStepBuilderWriteTo<TOutput>

Method Returns Description
WriteTo(IWriter<TOutput>) IStepBuilderOptions Sets the writer (interface)
WriteTo(Func<IEnumerable<TOutput>, Task>) IStepBuilderOptions Lambda writer
WriteTo(Func<IEnumerable<TOutput>, CancellationToken, Task>) IStepBuilderOptions Lambda writer with cancellation
WriteTo<TWriter>() IStepBuilderOptions Writer resolved from DI (AddNBatch jobs only)

Stage 4: IStepBuilderOptions

Method Returns Description
WithSkipPolicy(SkipPolicy) IStepBuilderOptions Sets the error skip policy
WithRetryPolicy(RetryPolicy) IStepBuilderOptions Sets the transient-failure retry policy
WithChunkSize(int) IStepBuilderOptions Sets the chunk size (default: 10)
WithListener(IStepListener) IStepBuilderOptions Registers a step-level listener

ITaskletStepBuilder

Method Returns Description
WithListener(IStepListener) ITaskletStepBuilder Registers a listener for the tasklet step

Core Interfaces

IReader<TItem>

public interface IReader<TItem>
{
    Task<IEnumerable<TItem>> ReadAsync(
        long startIndex, int chunkSize,
        CancellationToken cancellationToken = default);
}

IProcessor<TInput, TOutput>

public interface IProcessor<TInput, TOutput>
{
    Task<TOutput> ProcessAsync(
        TInput input,
        CancellationToken cancellationToken = default);
}

IWriter<TItem>

public interface IWriter<TItem>
{
    Task WriteAsync(
        IEnumerable<TItem> items,
        CancellationToken cancellationToken = default);
}

ITasklet

public interface ITasklet
{
    Task ExecuteAsync(CancellationToken cancellationToken = default);
}

IJobListener

public interface IJobListener
{
    Task BeforeJobAsync(string jobName, CancellationToken cancellationToken);   // default: no-op
    Task AfterJobAsync(JobResult result, CancellationToken cancellationToken);  // default: no-op
}

IStepListener

public interface IStepListener
{
    Task BeforeStepAsync(string stepName, CancellationToken cancellationToken);   // default: no-op
    Task AfterStepAsync(StepResult result, CancellationToken cancellationToken);  // default: no-op
}

Dependency Injection

ServiceCollectionExtensions

Method Description
AddNBatch(this IServiceCollection, Action<NBatchBuilder>) Registers NBatch services, job factories, and background workers

NBatchBuilder

Method Returns Description
AddJob(string name, Action<JobBuilder>) JobRegistration Registers a named job
AddJob(string name, Action<IServiceProvider, JobBuilder>) JobRegistration Registers a named job with access to DI services

JobRegistration

Method Returns Description
RunOnce() JobRegistration Runs the job once at startup, then the worker exits
RunEvery(TimeSpan interval, bool runImmediately = true) JobRegistration Repeats after each completion; optionally waits one interval before the first run
RunOnCron(string cronExpression, TimeZoneInfo? timeZone = null) JobRegistration Standard 5-field cron schedule (UTC default, skip-if-missed)

Jobs without a schedule are on-demand only — trigger them by injecting IJobRunner and calling RunAsync("job-name"). The last schedule call wins.

IJobRunner

public interface IJobRunner
{
    Task<JobResult> RunAsync(string jobName, CancellationToken cancellationToken = default);
}

Inject IJobRunner into controllers, endpoints, or services to trigger jobs on demand.


Result Types

JobResult

public record JobResult(
    string Name,
    bool Success,
    IReadOnlyList<StepResult> Steps,
    bool Cancelled = false,
    TimeSpan Duration = default)
{
    public JobResult EnsureSuccess();   // throws JobFailedException when Success is false
}

Cancelled is true when the run was cancelled; job listeners still receive the result before RunAsync rethrows the OperationCanceledException. EnsureSuccess() returns the result for chaining, or throws a JobFailedException (carrying the result and naming the first failed step).

StepResult

public record StepResult(
    string Name,
    bool Success,
    int ItemsRead = 0,
    int ItemsWritten = 0,
    int ItemsSkipped = 0,
    TimeSpan Duration = default);

ItemsSkipped counts individual skipped items.


SkipPolicy

Method Description
SkipPolicy.None Never skip (default)
SkipPolicy.For<TEx>(int maxSkips) Skip up to N items for one exception type
SkipPolicy.For<T1, T2>(int maxSkips) Skip for two exception types
SkipPolicy.For<T1, T2, T3>(int maxSkips) Skip for three exception types

Matching includes subclasses of the given types and walks each thrown exception’s inner-exception chain (up to 10 levels). See Skip Policies for the item-level scan behavior.


RetryPolicy

Method Description
RetryPolicy.None Never retry (default)
RetryPolicy.For<TEx>(int maxAttempts, TimeSpan? delay = null) Retry one exception type; maxAttempts includes the first try
RetryPolicy.For<T1, T2>(...) / For<T1, T2, T3>(...) Retry for two/three exception types
WithBackoffMultiplier(double multiplier) Returns a copy with exponential backoff

Same matching rules as SkipPolicy. Retries run before the skip policy is consulted. See Retry Policies.


NBatchDiagnostics

Member Description
SourceName ("NBatch") Name of the ActivitySource and Meter — use with AddSource(...) / AddMeter(...)

See Observability for the emitted activities, tags, and metrics.


Built-in Components

Class Type Package Description
CsvReader<T> Reader NBatch Delimited file reader with header parsing, RFC 4180 quoting, and header-to-property auto-mapping (new CsvReader<T>(path))
DbReader<T> Reader NBatch.EntityFrameworkCore EF Core paginated reader
DbWriter<T> Writer NBatch.EntityFrameworkCore EF Core bulk writer (detaches entities after save)
FlatFileItemWriter<T> Writer NBatch Delimited file writer

Package: NBatch.EntityFrameworkCore

The EF Core job store — install separately:

dotnet add package NBatch.EntityFrameworkCore

JobBuilderExtensions

Method Returns Description
UseJobStore(this JobBuilder, string connStr, DatabaseProvider provider = SqlServer) JobBuilder Enables SQL-backed progress tracking for restart-from-failure

DatabaseProvider

public enum DatabaseProvider
{
    SqlServer,    // Microsoft SQL Server
    PostgreSql,   // PostgreSQL via Npgsql
    Sqlite,       // SQLite
    MySql         // MySQL / MariaDB via Pomelo (.NET 8 & 9 only)
}

Next: Examples →


Back to top

NBatch — lightweight batch processing for .NET.