Hi all.
I have a server with more than 500 databases with the same structure and I would like to know how I can implement a connection factory with SnapObjects. And how to connect dynamically to each one these.
Regards
Hi all.
I have a server with more than 500 databases with the same structure and I would like to know how I can implement a connection factory with SnapObjects. And how to connect dynamically to each one these.
Regards
Hi Juan,
please allow me a few criticisms on your solution, which however is very valuable as it raises awareness of the problem of binding cachenames dynamically.
This said, I thank you again for paving the way on how to handle this problem in SnapObject's DataContext object and AddDataContext function. With the help from Appeon, I attach a simpler solution that avoids the four flaws above.
Goal is to parameterise cachenames, which for example can be sent by the client as easy as in the http request's header:
restclient.SetRequestHeaders( "CacheName:"+ ls_CacheName )
restclient.Retrieve(dw_dept, "https://localhost:5001/api/Department/Retrieve")
The API wil rely on same concept of data context factory you posted
services.AddScoped<DefaultDataContext>(provider => provider.GetService<DataContextFactory>().CreateDataContextSQL())
but it accesses current HttpContext and Config to build the connection string dynamically:
public DataContextFactory(IConfiguration config, IHttpContextAccessor httpAccessor)
{
_config = config;
_httpAccessor = httpAccessor;
}
public DefaultDataContext CreateDataContextSQL()
{
string cacheName = _httpAccessor.HttpContext.Request.Headers["CacheName"].ToString();
string connectStr = _config[$"ConnectionStrings:{cacheName}"];
var options = new OdbcSqlAnywhereDataContextOptions(connectStr);
return new DefaultDataContext(options);
}
Best,
.m
Hi Juan,
The following points may be helpful for creating your DataContext factory:
1. Pass in the connection string to construct the DataContextOption object.
E.g.:
new SqlServerDataContextOptions(connectionString)
2. Pass in DataContextOptions object to construct the DataContext.
E.g.:
public class SampleDataContext : SqlServerDataContext
{
public SampleDataContext(IDataContextOptions options)
: base(options)
{
}
}
3. Create a DataContextFactory class which can create corresponding DataContext object based on the key of the connection string. Depending on your business logic, you might want to consider the database type in the DataContextFactory class.
4. Inject the DataContextFactory into the DI framework (note the lifetime), then receive and use it in each service to get DataContext.
Regards,
Logan
You could help me to implement something similar to this
https://dzone.com/articles/dynamic-connection-string-in-net-core
or something similar that helps me manage multiple connections to different databases and change them in execution time.