Search code examples
c#dispose

How to implement Dispose to custom function in C#?


I have the sample class as listed below an I need to open the db connection using CreateDataConnection() every time I call an API.

public class FlowerController : ApiController
    {
        DataConnection oDataConnection { get; set; }
        public void CreateDataConnection() 
        {
            ConnectionParameters oParams = new ConnectionParameters();

            oParams.strDatabaseName = "123123123123";
            oParams.strPassword = "123123123123";  
            oParams.strSchemaName = "123123123123";
            oParams.strServerIP = "192.168.1.1";
            oParams.strServerPort = "12313";
            oParams.strUsername = "123123123";
            oDataConnection = new DataConnection(oParams);
        }

        [HttpPost]
        [AllowAnonymous]
        [Route("api/flower/Activate")]
        public DBStatus Activate(W_Flower oFlower)
        {
            CreateDataConnection();
            DBStatus result = oDataConnection.Activate(oFlower);
            return result;
        }
}

I want to implement Activate API as below

public DBStatus Activate(W_Flower oFlower)
{
   using (CreateDataConnection())
   {
       DBStatus result = oDataConnection.Activate(oFlower);
   }
   return result;
}

But this does not work as I do not have dispose method in CreateDataConnection. How can I implement dispose here? I have not done this method before.


Solution

  • Change CreateDataConnection to return the newly created connection,

    public DataConnection CreateDataConnection() {
        ConnectionParameters oParams = new ConnectionParameters();
    
        oParams.strDatabaseName = "123123123123";
        oParams.strPassword = "123123123123";  
        oParams.strSchemaName = "123123123123";
        oParams.strServerIP = "192.168.1.1";
        oParams.strServerPort = "12313";
        oParams.strUsername = "123123123";
        return new DataConnection(oParams);
    }
    

    instead of storing it in a property.

    Then you can do just

    public DBStatus Activate(W_Flower oFlower) {
       using (var connection = CreateDataConnection()) {
           return connection.Activate(oFlower);
       }
    }