I have a number of static repository classes that hold and retrieve data objects. I want to provide some common functionality to them, so I have them inherit from an abstract class.
This doesn't work, since static classes are not allowed to inherit. I trust in the .NET design, so I will accept that this is for good reason.
So this leads me to believe I have some fundamental design issues here.
My question is how do I design my code to achieve the result I'm looking for? Or, is it just a matter of having to replicate the methods across all my classes. Perhaps a singleton?
Static Repo:
public static class CreditMemos : InvoiceRepository<CreditMemo>
{
public static List<CreditMemo> GetByDocumentNumber(string documentNumber)
{
return CheckCache(
ConvertReaderToCreditMemos(
Invoices.GetByDocumentNumber<CreditMemo>(documentNumber)));
}
}
Desired Base:
abstract class InvoiceRepository<t>
where t: DataObjects.Invoice
{
static List<t> invoiceCache = new List<t>();
static protected List<t> CheckCache(List<t> results)
{
foreach (var result in results)
if (!invoiceCache.Any(p => p.ID == result.ID))
invoiceCache.Add(result);
return invoiceCache.Where(p => results.Any(a => a.ID == p.ID)).ToList();
}
}
You could just drop the static from your inheriting classes, and make them work similarly by hiding the constructor:
public sealed class CreditMemos : InvoiceRepository<CreditMemo>
{
private CreditMemos() { }
...
Or you can make InvoiceRepository<t> its own static class, and instead of inheriting, you just use the methods in your other static classes. (by the way, the convention is to capitalize the first letter in all type names, including generic types, so T, not t)
public static class CreditMemos
{
public static List<CreditMemo> GetByDocumentNumber(string documentNumber)
{
return InvoiceRepository<CreditMemo>.CheckCache(new List<CreditMemo>());
}
}
public static class InvoiceRepository<T>
where T: DataObjects.Invoice
{
static List<T> invoiceCache = new List<T>();
static internal List<T> CheckCache(List<T> results)
{
foreach (var result in results)
if (!invoiceCache.Any(p => p.ID == result.ID))
invoiceCache.Add(result);
return invoiceCache.Where(p => results.Any(a => a.ID == p.ID)).ToList();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With