OK, I may be asking for the impossible, but I'll give it a shot: For a case
like this:
using System.Data.SqlClient;
abstract class Base
{
private SqlConnection DBConnect;
Base(string SqlConnectStr)
{
DBConnect = new SqlConnection(SqlConnectStr);
}
// Some other base code here that relys on the DBConnect object
}
sealed class Derived1 : Base
{
Derived1(string ConnectStr):base(ConnectStr)
// etc
}
sealed class Derived2 : Base
{
Derived2(string ConnectStr):base(ConnectStr)
void func()
{
Derived1 DerivedObject;
// here I would like DerivedObject to inherit the Base class already
// instantiated by Derived2 (so that it uses the same SQL Server
connection), rather than creating it's own instance
DerivedObject = new Derived1();
}
}
I would like for Derived2 to pass the SqlConnection that Base has created
for it along to Derived1 when it creates an object for it; from my thinking,
it would be nice if there was some way to force Derived1:Base to accept
Derived2:Base's object rather than instantiating its own.
I can think of two potential solutions, neither of which is very appealing
to me. The first is to create a new Base constructor that takes a
SqlConnection, and make it's internal SqlConnection protected.
Unfortunately, this is code in a DLL, and because C# has no concept of
friend classes, this creates a sort-of "backdoor" situation whereby a) any
derived class from Base can mess with the SQL Server Connection, and b) it
creates an unwanted API interface that allows "unauthorized" code to inject
a SQL Server connection. The other solution would be to simply pass the
ConnectStr string and create a new SQL Connection, but I would also like to
limit the number of connections that I make if possible because there exists
the potental for a lot of database connections already within the scope of
the overall app.
Any other solutions to my dilemma?