Giorgi / EntityFramework.Exceptions

Strongly typed exceptions for Entity Framework Core. Supports SQLServer, PostgreSQL, SQLite, Oracle and MySql.
https://giorgi.dev/entity-framework/introducing-entityframework-exceptions/
Other
1.44k stars 68 forks source link

Added ability to add ExceptionProcessorInterceptor to ServiceCollection #42

Closed uhfath closed 2 years ago

uhfath commented 2 years ago

In some cases where there is no possibility to use DbContextOptionsBuilder this extension adds an ability to use IServiceCollection to add ExceptionProcessorInterceptor to a list of services with a service type of IInterceptor. Later this could be used to add interceptors where appropriate using IServiceProvider.

For example. Our project uses this to setup a Db context:

services
    .AddDbContext<MedServiceDbContext>((srv, opts) => opts
        .AddInterceptors(srv.GetServices<IInterceptor>())
        .UseNpgsql(configuration.GetMedServiceDbConnectionString()))
;

And there is no way to alter this behavior or subclass a MedServiceDbContext to change it's OnConfiguring. This PR adds a helper method to cases like this without hurting any backward compatibility.

To use it simply call AddExceptionProcessor on a IServiceCollection like usual (i.e. services.AddExceptionProcessor somewhere in ConfigureServices or elsewhere where appropriate) and then when configuring a DbContext use the code like above.

Giorgi commented 2 years ago

Isn't opts instance of DbContextOptionsBuilder ? Why don't you use the non generic UseExceptionProcessor method?

uhfath commented 2 years ago

Isn't opts instance of DbContextOptionsBuilder ? Why don't you use the non generic UseExceptionProcessor method?

Yes. opts is indeed of DbContextOptionsBuilder type. The issue is that we can't alter this setup sequence. I've just showed it as an example. The only way in our case is through interceptors which has to be registered beforehand. But this project uses internal visibility for them and that's why I've added a PR. Perhaps someone else might come across same limitation in their projects. It doesn't seem to hurt anything.

Giorgi commented 2 years ago

I see. Can you also add tests? Just verify that the correct type gets resolved from the container.

sonarcloud[bot] commented 2 years ago

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
No Duplication information No Duplication information

uhfath commented 2 years ago

Sure. Added appropriate tests. But also I had to InternalsVisibleTo project setting to all the .csproj files so tests would have access to internal classes, which interceptors currently are.

uhfath commented 2 years ago

Do you have any plans on merging this for the next release?