The SqlKata documentation lists the following code:
.NET 6
builder.Services.AddTransient<QueryFactory>((e) =>
{
var connection = new SqlConnection(CONST.KenticoConnectionString);
var compiler = new SqlServerCompiler();
return new QueryFactory(connection, compiler);
});
HomeController.cs
using SqlKata;
using SqlKata.Execution;
public class HomeController {
private readonly QueryFactory db;
public HomeController(QueryFactory db) {
this.db = db;
}
public IActionResult Index() {
// Here books is of type `IEnumerable<dynamic>`
var books = db.Query("Books").Where("IsPublished", true).Get();
// or `IEnumerable<Book>` if using the Generic overload
var books = db.Query("Books").Where("IsPublished", true).Get<Book>();
return Ok(books);
}
}
How would I go about using multiple QueryFactory? I have two different databases that I need to query which have separate connection strings.
I can set up multiple QueryFactor within Program / Startup, but I have no idea how to inject the correct one.
You can create a factory for
QueryFactorythat will dynamically return you an instance with dynamically injectedConnectionString:It should be registered in your
ServiceCollection:After that, you can inject your factory to the controller and get the needed
QueryFactorybased on the connection string provided you can get fromIConfiguration(or in any other way):It is also possible to create the separate derived class for each of your connection strings and register them in IoC, however, this is a bad approach, to avoid which the factory pattern was invented as well:
The main benefits of factory over the second approach are: