Sharing an Oracle connection across multiple data handlers - c#

I have a solution in which an UpdateController class manages the logic for updating data. This controller calls various classes for managing data (ClaimData, StatementData, etc.). What's the best way to share connection across these data handlers--use a singleton, or create another class for managing the connection and passing it to each data handler? What if the application is multithreaded?
Thanks in advance.

you could use dependency injection to provide each of these with a connection...
another way is to use an Oracle provider with internal Connection pooling (for example Devart dotconnect, I am only a customer)... then you only share the connection string via dependency injection or configuration file... every class instantiates/releases the connection on its own... the central connection pooling takes care of the rest (reusing connections etc)... this way you don't have to worry about any threading issues regarding connections...

Related

What is the best practices to connect to postgresql from microservice

I have a multi tenant c# project with 60 microservices connected to multiple postgresql databases. I'm using open/close connection on each transaction. I'm not sure that this is the best practices.
Do I have to open one connection to each database on each microservice and use it on all my activities or open/close on each transaction
You should consider use Unit of Work pattern plus Dependency Injection practices.
I let you here a Microsoft document explaining the Unit of Work pattern
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
If this approach isn´t valid for you, using only ORMs like Dapper or Entity Framework should be another approach, but in this case I strongly recommend you to isolate this in "repositories" entities. This way, everytime you instance and use a repository (using Dependency Injection) you won´t have to deal with transaction details (the connection will be opened every time you instance this entity and closed when you call Dispose method).

SqlConnection and HttpContext

Could I store a SqlConnection in the HttpContext?
I mean, how can I share a single SqlConnection across multiple classes?
In my project every class inherits a base abstract class that open and close connection.
This class recognizes if a SqlConnection was opened by another class in that case uses it.
I can store this connection in another way that isn't HttpContext?
There is another method to do this, exp. pass the connection between layers?
THX
I wonder why you need to store a single SqlConnection. It doesn't smell great.
If you really do need to share a single SqlConnection across multiple classes, dependency injection is likely a better option. Have a connection factory instantiate a connection object and pass it around as required.
Otherwise, let the DBMS worry about controlling your connection resources. Create, open and close a connection each time you need one.
You are going wrong way. You shouldn't follow this thinking unless you need to share transaction context as mentioned by Lasse V. Karlsen mentioned in his comment. If you are worried about performance and thi is the reason why you want to keep one connection open and shared then it also wrong. In case of e.g. ADO.NET you have connection pooling. This means that even though you call close on connection it is not closed, it is returned to the pooler. This is a mechanism that keeps track of connections and maximizes efficiency by managing them. If you call Open to get a new connection then under the hood you may get an existing one that was used a few minutes before and that was still kept open by the pooler and returned back for reuse. So, if the motivating force is efficiency, then it is not a path you should follow. It is already taken care of on a lower level. Refer to http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx .

Best practice for Window Forms and SQL connection instance

What is best practice for C# Window Forms and SQL connection instance. I need the same SQL connection in all window forms. What is best implementation practice for this? Where do I put the SQL connection?
I am using Compact framework 3.5.
Personally I prefer to leave connection management to the ADO.NET connection pool and everytime I want to query:
using (var conn = new SqlConnection("connection string"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// ...
}
}
}
When you call conn.Open() a physical connection is not opened, it is drawn from the connection pool, and when the using block end and invokes .Dispose the connection is not closed but returned to the connection pool in order to be reused. This improves performance and relieves me from worrying about where to put or store those SqlConnection instances in applications.
You say you need the same connection in all your forms, but I don't think you should consider that to be axiomatic. You may well need to connect to the same database in all forms, but that's not the same thing - any more than you would need to use the same connection to make multiple requests to a web service.
I would strongly suggest three things:
Use dependency injection to allow a single object to be provided to multiple classes/objects which all need it
Don't inject the actual connection: inject something which can provide a connection, or perhaps just something which can execute a query for you.
Take code which accesses the database out of the user-interface code so you can test each independently of the other.
Generally speaking, database access should be (from the caller's point of view): "open connection, do work, close connection whatever happened" (as per Darin's answer). Let .NET's connection pooling take care of the physical connection to the database. How you structure your code around that will depend on your requirements, and the extent to which they vary between forms. In many cases you may be able to get away with just asking your database access class to execute a query for you with a certain set of parameters and return the results - in other cases you may need more fine-grained control.
As Dimitrov suggested a good approach is to open and close connections only when needed and keep it open the shortest possible time. .NET Connection pool will handle this for you so connections will be reused in a transparent way for you.
In general a good approach is to have another class library to serve as Data Access Layer which wraps the calls to database and does not expose any connection or command usage to the UI, so in the future you would be able to move to another database engine, if needed, changing only the DAL.
Communication from DAL and UI should consist only in objects (entities) or for simple projects DataTables and DataSets. In most of the cases a third project (class library) is in the between and it's called Business Logic, such level manipulates the data from DAL and applies your application specific business logic returning cleaner or elaborated results to the UI.
I have used this approach in many projects already, since about 11 years.
You should make a class with the connection logic in.

C# + MySQL Connections

I am currently working on a C# (.NET) project which connects to a MySQL Community Server database and runs some queries. There are currently 4 classes which use their own MySQLConnection object (I'm using the MySQL .NET connector), in order to connect to the database.
Is this good practice, or should I use one 'global' (static?) connection? Using one single connection is kind of against my habits of structuring the code. Not a big fan of 100000 objects working with one shared static field. I bet it's against most programmers' views too.
I also noticed that once I call connection.Close(), the connection does not necessarily get closed. Trying to .Open() it again would result in an exception. I trust this is because I did not set "Pooling=False" in the connection string. I'll experiment with it. If you have any thoughts on this one too, feel free to drop them here.
So, in short, I'd like some opinions on how to organize my MySQLConnections. If you think a single static MySQLConnection to be used by all of the program's classes is better (not necessarily performance-wise, I'm talking more about the effect of multiple MySQLConnections on the database system itself), let me know why you think so.
I'm expecting for the final program to have around 10 or 15 classes, each actively querying the database.
My rules of thumb are:
keep connections open for as brief a time as possible
let ADO.NET handle connection pooling for you
share connections only when the processes are particpating in a transaction together
So, no you should not use one global static connection. But you could have a utility method that supplies your data fetching methods with an open connection. Then you would do something like (assuming Sql is your utility class):
public IEnumerable<MyClass> GetSomeData()
{
using (var cn = Sql.GetOpenConnection())
{
//get your data here
}
}
You can continue with one connection per class. Most ADO.NET providers use connection pooling per default as you have noticed. Close doesn't really close the connection but return the connection to the pool. However, you should not try to Open() the connection again but create a new connection object.
There is one downfall with using one connection per class and that's transaction handling. Transactions can not be shared over multiple connections (unless you are using TransactionScope).
I usually prefer one connection per "session" and take in the connection in the constructor to my repository classes. (As I usually use inversion of control containers). Google a bit about Unit Of Work implementations.
Do not create a single shared connection. Open as late as possible and close as early as possible. If you need to use a connection for multiple queries, try looking at MARS (multiple active record sets) I don't know if MySQL connector supports that though.
certianly let the system handle connection pooling. db connections are expensive.
public class DALCommon
{
public static string GetConnectionString
{
//return System.Configuration.ConfigurationManager.AppSettings["connectionInfo"];
get
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string server = appSettings["server"];
string userid = appSettings["userid"];
string password = appSettings["password"];
return String.Format("server={0};user id={1}; password={2}; database=dbmystock; pooling=false", server, userid, password);
}
}
}

Proper abstraction of the database tier in a 3 tier system?

I am creating a 3 tier application. Basically it goes
Client -> (through optional server to
be a thin-client) -> Business Logic ->
Database Layer
And basically making it so that there is never any skipping around. As such, I want for all of the SQL queries and such to be in the Database Layer.
Well, now I'm a bit confused. I made a few static classes to start off the database tier but what should I do for the database connections? Should I just create a new database connection anytime I enter the Database Layer or would that be wasteful? Does Connection.Open() take time whenever you have a ConnectionPool?
To me, it just feels wrong for the Business tier to have to pass in a IdbConnection object to the Database tier. It seems like the Database tier should handle all of that DB-specific code. What do you think? How can I do it the proper way while staying practical?
Because of the ConnectionPool, open a new connection each time you access the db is usually not a problem.
If you can reuse open connection without leaving connections open a long time, and without risking leaving orphaned opened connections, then it doesn't hurt to reuse open connections. (I actually inject a datatool into all my classes that access the db. This is mainly for unit testing purposes, but it also allows me to optionally keep a connection open to be used by multiple calls to the db.)
But again, you should not stress too much about opening/closing a lot of connections. It is more important that your DAL:
is maintainable, simple, flexible
performs as well as possible
(most importantly) always properly disposes of it's connections.
Only open the connection when you need it.
Do not maintain a connection to the database, that is much more wasteful.
Of course your db layer will open the connection, Im not sure why you think the BLL is going to pass a connection to the db. The BLL does not know about the database (at least it shouldnt), it should handle business rules and such. The actual connection is open at the db layer.
Here is a link that shows how the BLL should look:
Validating data in .net
The connection string itself should simply be a private string variable within your db layer class and you should be able to pull connection string information from say a web.config file.
It's okay to create and open a new connection every time you enter the database layer, and close the connection as soon as you're finished with it. .Net/Sql Server handles connection pooling well enough to make this work, and it's the accepted way to do it.
You are also right that you don't pass your connection string in from the business layer. That should be a private (but configurable) member of the data layer.
Traditionally, a separate "Data Access Layer" provides the database context for retrieving and committing data. There are several well-known patterns for this, such as Repository. ADO.NET implements several others, such as Provider.
Entity Framework and LINQ to SQL are also good options to further encapsulate and simplify the isolation of the data tier.
You can create a class (or namespace of classes, depending on the size) to host the database layer. Within your database class, you should just use a connection pool in the database layer. The pool will keep n number of connections open to the database at any given time, so you can just run a query using one of the pooled connections without incurring significant overhead.
With this in place, your database layer should present an "API" of public methods that the business layer can call into. None of these methods should expose a database connection object - those details are internal to the data layer.
Then from your business layer, just call into the database layer's "API" each time you need to run a query.
Does that help?

Categories