I currently have the following working code. I am looking for some suggestion with best practices and perhaps a better way to accomplish my goal.
Goal: - in short - Have a generic data interface as a single data access point to different data sources.
Concern: My current code is working fine but I have to call GetRepository()
in each method inside my test class to access the desire instance of the data source repository.
Code Snippet:
public class GenericRepository : IGenericRepository
{
public T GetRepository<T>()
{
string typeName = typeof(T).ToString();
if (string.IsNullOrEmpty(typeName))
return default(T);
Type repoType = Type.GetType(typeName);
object repoInstance = Activator.CreateInstance(repoType);
return (T)(object)repoInstance;
}
// more code...
}
Usage:
public class MyTestClass
{
IGenericRepository repo = new GenericRepository();
private void DoThis()
{
IFileRepository repoA = repo.GetRepository<FileRepository>();
// now I can call repository A interface methods like this repoA.SomeMethod()
}
private void DoThat()
{
ISQLRepository repoB = repo.GetRepository<SQLRepository>();
// now do something with repository B interface methods like this repoB.SomeMethod()
}
}
I thought of an alternative way to do this but it has its own drawbacks as well.
Implement the interface methods in both
IGenericeRepository
and as well as the interface I inherited.Implement the methods for inherited interface inside IGenericRepository and put it in each different region and end up with a massive page of code
Thoughts? Comments? Suggestion? -- I personally think the first option is a better choice but wonder if there are better ideas or maybe there is something wrong with my implementation.
Alternative Code
public class GenericRepository : IGenericRepository, IFileRepository, ISQLRepository
{
public FileRepository fileRepo { get; set; }
public SQLRepository sqlRepo { get; set; }
public GenericRepository()
{
fileRepo = new FileRepository();
sqlRepo = new SQLRepository();
}
// more code...
}
Alternative Usage
public class MyTestClass
{
IGenericRepository repo = new GenericRepository();
private void DoThis()
{
// now I can access file repository like this: repo.fileRepo.SomeMethod();
// now I can access sql repository methods like this: repo.sqlRepo.SomeMethod();
}
private void DoThat()
{
// now I can access file repository like this: repo.fileRepo.SomeMethod();
// now I can access sql repository methods like this: repo.sqlRepo.SomeMethod();
}
}
====== updated:
To provide more context. Below is the solution structure
-- Solution
---- Repository Project (GenericRepository, FileRepository, SQLRepository)
---- IRepository Project (IGenericRepository, IFileRepository, ISQLRepository)
---- MyTestProject Project (MyTestClass)
T
is used both forIFileRepository
andFileRepository
– TopinFrassi Oct 15 '14 at 18:18T
overridesToString
, the whole thing falls apart... – Mat's Mug♦ Oct 15 '14 at 18:19