Hi I am wanting to create a base class to inherit from but I am having some problems.
I have two classes which do almost identical work but get the data which they work with from different databases and use different internal data structures to manipulate the data.
I want to have virtual doSomething method in the base and ideally virtual dataAccess method in the base also.
The second problem can be solved through the use of generics but I cant use generics to solve the first problem as the constructor of the DBMl context I use is not parameterless.
Am I going about this all wrong. I am trying to be DRY but seem to be working against inheritance.
Example code below.
class Foo {
private _ctx DBML.Database1; // Inherits from System.Data.Linq.DataContext
public Foo(string constring) {
_ctx = new DBML.Database1(constring);
}
private DoSomeThing() {
FooDataObj = DataAccess(1);
}
private FooDataObj DataAccess(int ID)
{
var v = from t in _ctx
where t.Id = ID
select new FooDataObj(t);
return v
}
}
class Bar {
private _ctx DBML.Database2; // Inherits from System.Data.Linq.DataContext
public Bar(string constring)
{
_ctx = new DBML.Database2(constring);
}
private DoSomeThing() {
BarDataObj = DataAccess(1);
}
private BarDataObj DataAccess(int ID) {
var v = from t in _ctx
where t.Id = ID
select new BarDataObj(t);
return v
}
}
FooandBarshould not call the database constructor by themselves, the database object should be a parameter of the constructor (instead of the connection string). This principle is called Dependency Injection and will solve most of your problems. Should be easy then to create a new generic classDataObjFactory<DataObjType>as a replacement for Foo and Bar.