hryz / Dapper.Logging

Integration of the DbConnection and Asp.Net Core Logging
MIT License
43 stars 15 forks source link

Multiple connections to different databases #5

Closed HubertoKusters closed 4 years ago

HubertoKusters commented 4 years ago

I have the situation that I need two connections to different databases. For both connections I want to make use of the DbConnectionFactory, but as it is now implemented we must register the DbConnectionFactory via the extension methods in the DI. This means that I can only have one DbConnectionFactory in the DI and there is no way as far as I can see that I can specify a DbConnectionFactory per service via a factory registration. This is due to the fact that all classes are internal.

Can this be solved?

TIA

hryz commented 4 years ago

Hello, @HubertoKusters,

I wasn't going to make the factories public to prevent the future breaking changes. However, for enabling your scenario I prototyped an approach with a public factory provider and I didn't like it. It adds an extra layer of abstraction (along with complexity), but the interface of its methods mirrors the factories and will be broken in case of a change in the factories. That's why I made factories public in v0.4 of the NuGet. Please update the package. Also, I added tests, one of them is for your scenario: https://github.com/hryz/Dapper.Logging/blob/master/tests/Dapper.Logging.Tests/MultipleConnectionsTest.cs

PS: Also, I added more features (logging a connection, passing an extra context to logs, low-level API for hooks without a predefined effect).

hryz commented 4 years ago

Hey, @HubertoKusters,

I'm going to close this issue since I've done what you requested. If this still doesn't work for you please feel free to reopen it.

HubertoKusters commented 4 years ago

Thanks for the quick response and sorry for my delayed response.

I now solved it this way:

serviceCollection
    .AddDbConnectionFactoryWithCtx<Context1>(
        provider => new SqlConnection(ConnectionString1),
        builder => builder.WithLogLevel(LogLevel.Debug).WithSensitiveDataLogging())
    .AddDbConnectionFactoryWithCtx<Context2>(
        provider => new SqlConnection(ConnectionString2),
        builder => builder.WithLogLevel(LogLevel.Debug).WithSensitiveDataLogging())

This way I can now inject either IDbConnectionFactory<Context1> or IDbConnectionFactory<Context2> in my services.

Thank you again.