We are bulding a system that we want the final implementation do "hide" the data access layer (so that we can change it in the future).
So the idea is that the application code will call an interface that will be implemented by Database access objects. So we have the interface class:
public interface DatabaseInterface
{
void Create(DataObject obj);
}
Then we have the class that implements the interface:
public class DatabaseAccess : DatabaseInterface
{
void Create(DataObject obj)
{
Entity dbContext = new Entity();
dbContext.Data.Add (obj);
dbContext.SaveChanged();
}
}
Together will all this, we have the DataObject class:
public class DataObject
{
integer Data1;
string Data2;
}
OUr problems sits on the main application, as I don´t know what is the DatabaseInterface implementation:
public class CreateElementOnDatabase
{
DataObject myObj = new DataObject();
myObj.Data1 = 10;
myObj.Data2 = "Test String";
var dbAccess = new DatabaseInterface() <=== I know this is not possible, but don´t know what to do!!!!
dbAccess.Create (myObj);
}
How do I call the implemented method without knowing which class did it ? Surely I´m missing something on my design.
We REALLY wanna make the application fully independent from the code below.
[EDIT 1]
These implementations reside in different class libraries. So I have the following: App project DatabaseInterface project DatabaseAccess project DataObject project
what you are missing is a "factory" class that builds instances for outside world based on parameters or configuration settings it receives (if they want to have the outside world influencing its behavior) or make their own decisions, i.e. they will create the instances of either type A or B based on their internal logic that cannot be changed from the outside. In the code below you will see the DatabaseFactory which is what you were missing. Also, note the private/public/internal modifiers which are important to make sure you expose what is needed and not more than you need (making all classes public creates confusions to those who want to use your library)
Here is the code