dotnetcore/CAP · error · InvalidOperationException
We detected that you are using ICapPublisher in DbContext…
Error message
We detected that you are using ICapPublisher in DbContext, please change the configuration to use the storage extension directly to avoid circular references! eg: x.UsePostgreSql()
What it means
Error "We detected that you are using ICapPublisher in DbContext, please change the configuration to use the storage extension directly to avoid circular references! eg: x.UsePostgreSql()" thrown in dotnetcore/CAP.
Solutions
- Remove ICapPublisher usage from your DbContext and configure CAP storage with the storage extension: services.AddCAP(x => x.UsePostgreSql(Configuration.GetConnectionString("..."))).
- For transactional publishing inside DbContext, use the CAP storage extension on DbContext options (options.UsePostgreSql().UseCAPTransaction(...)) instead of injecting the publisher.
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at src/DotNetCore.CAP.PostgreSql/CAP.PostgreSqlOptions.cs:51 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of dotnetcore/CAP@e52b8508e5 (2026-09-14).
Data as JSON: /api/errors/0413a87e69ab46ff.
Report an issue: GitHub.
Appendix: source
Thrown at src/DotNetCore.CAP.PostgreSql/CAP.PostgreSqlOptions.cs:51
return DataSource != null ? DataSource.CreateConnection() : new NpgsqlConnection(ConnectionString);
}
}
internal class ConfigurePostgreSqlOptions : IConfigureOptions<PostgreSqlOptions>
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public ConfigurePostgreSqlOptions(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
public void Configure(PostgreSqlOptions options)
{
if (options.DbContextType == null) return;
if (Helper.IsUsingType<ICapPublisher>(options.DbContextType))
throw new InvalidOperationException(
"We detected that you are using ICapPublisher in DbContext, please change the configuration to use the storage extension directly to avoid circular references! eg: x.UsePostgreSql()");
using var scope = _serviceScopeFactory.CreateScope();
var provider = scope.ServiceProvider;
using var dbContext = (DbContext)provider.GetRequiredService(options.DbContextType);
var coreOptions = dbContext.GetService<IDbContextOptions>();
var extension = coreOptions.Extensions.First(x => x.Info.IsDatabaseProvider);
options.DataSource = extension.GetType().GetProperty(nameof(options.DataSource))?.GetValue(extension) as NpgsqlDataSource;
if (options.DataSource == null)
{
options.ConnectionString = extension.GetType().GetProperty(nameof(options.ConnectionString))?.GetValue(extension) as string;
}
}
}View on GitHub (pinned to e52b8508e5)