Reduce usage in C #

My question may be stupid or may not be a question at all, but here it goes.

I perform some operations with the database in my project ASP.net MVC, where I create two objects each time, namely SqlConnectionand SqlCommand.

I showed an example below

using (SqlConnection connection = new SqlConnection(connectionString))
{
  using (SqlCommand command = new SqlCommand("sRegisterUser", connection))
  {

I perform all these different operations inside the same class with different methods.

My question is: how can I reduce the creation of these objects every time? How can I create them globally

PS: sRegisterUser is a stored procedure, since other other methods use different procedures that receive different values ​​as parameters.

Please help me.

Thanks for any help in advance.

+4
3

: . , .

+11

. , . , , .

, using?

using Windows.

, using:

SqlConnection connection = new SqlConnection(connectionString);
connection.Close();
connection.Dispose();

using , . using .

, :

SqlConnection connection;

try
{
    connection = new SqlConnection(connectionString);

    ...

    connection.Close();
}
finally
{
    connection.Dispose();
}
+3

, , . ADO.NET . , .

, , , , , .

, using:

using (var cn = new SqlConnection(yourConnectionString))
using (var cmd = new SqlCommand(yourQuery, cn))
{
    // do stuff
}

IDE , .

:

public static class Procedures
{
    public static void RegisterUser() // add whatever parameters you need
    {
        using (var cn = new SqlConnection(yourConnectionString))
        using (var cmd = new SqlCommand(yourQuery, cn))
        {
            // do stuff
        }
    }
}

, :

Procedures.RegisterUser();

factory pattern . , (.. ).

You can also be creative and combine two patterns. A custom class that implements IDisposablecan take care of creating the necessary ADO objects, open a connection, fulfill your request, close the connection and get rid of any objects that need to be disposed of when they are deleted.

Make a choice.

+1
source

Source: https://habr.com/ru/post/1539003/


All Articles