Placing a Configuration connection string in the Class so it can be viewed and use by all classes

Adding configuration manager in namespace so it can be visible to all the classes is not possible as below

Public string cs = ConfigurationManager.ConnectionStrings["ProductCalls"].ConnectionString; >>>>>> This does not work.

It seems that it works only if code is place inside each Public classes.


Namespace ABC



{
    Public Class XYX
{
 ,,,,,,,,}

Public Class XXX
 {
    }

Public Class ZZZ
{

   }
zachvaldezAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chinmay PatelChief Technical NinjaCommented:
Hi Zachvaldez,

Ideally you write a class, say DataAccess and then in that class

internal static SqlConnection GetConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["ProductCalls"].ConnectionString); 
}

Open in new window

Please tweak the code as I wrote it without IDE, it can be improved a lot. Error handling can be added and connection usage can be optimized even further by making this connection limited to DataAccess class only and have various methods like
ExecuteSQLReader, ExecuteDataSet, ExecuteInsert, etc.. (This is how Microsoft Enterprise Library handles DataAccess) so that your connection is only utilized via this DataAccess Class only.

So, XYX, XXX, ZZZ whenever you need to perform a data operation, you will do something like this...

Class XYX{
internal DataSet GetXYXDataSet()
{
DataAccess.ExecuteDataSet(XYXQuery);
}
}

Open in new window


Regards,
Chinmay.
0
Chris StanyonWebDevCommented:
Another approach (maybe more inline with OOP) is to write a data access class that contains your connection string (as a property or method), along with any other methods and properties that you need to share.

You can then either inherit from it (maybe implemented as an abstract class), or dependency inject it - very easy to do if you're using a DI Framework, such as AutoFac.
0
Dustin SaundersDirector of OperationsCommented:
@zachvaldez

As Chinamy pointed out, but a little explanation.

The difference is a static class, which doesn't have to be instanced to call it, and you can call it from your instances of other classes.

Quick Example:
 public class Sample1
    {
        public Sample1(Guid id, string value)
        {
            _id = id;
            Value = value;
        }

        private Guid _id;
        
        public Guid ID { get { return _id; } }
        public string Value { get; set; }
        
        private string SaveQuery
        {
            get
            {
                return "UPDATE Table SET Value = @value WHERE Id = @id";
            }
        }

        public void Save()
        {
            using (var _cs = StaticSample.GetSqlConnection())
            {
                SqlCommand sqlCommand = new SqlCommand(SaveQuery, _cs) { CommandType = CommandType.Text };
                sqlCommand.Parameters.Add("value", SqlDbType.VarChar).Value = Value;
                sqlCommand.Parameters.Add("id", SqlDbType.UniqueIdentifier).Value = ID;

                _cs.Open();
                sqlCommand.ExecuteNonQuery();
            }
        }
    }

    internal static class StaticSample
    {
        internal static SqlConnection GetSqlConnection()
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["ProductCalls"].ConnectionString);
        }
    }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris StanyonWebDevCommented:
@Dustin - not a great example - you're hardcoding the connection into the class, which makes testing impossible. You'll also create a new connection for every query you run. Not great on performance.

The cons of a static class (not an embedded one like above) is it's effectively a global variable, accesible to all sorts of other classess. This may be a quick-fix to a problem, but it'll be more robust if you just inject an instance to only those classes that need it. And for testing - just register a different class with the IoC.
0
Dustin SaundersDirector of OperationsCommented:
Not sure what your qualms are with the quick example, demonstrating how to call the static class from an instanced class.

There is plenty of utility in using the static class as such, and you should wrap your queries in using blocks or close the connections.  Are you forgetting about Connection Pooling?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.