lundi 9 mars 2020

C# save class type as preprocessor

Is in C# possible to save class type as preprocessor directive like in C/C++?

I have multiple services with a lot of shared code. Main difference is in calling correct DbSet & using correct class.

From following code to:

public class TaxService
{
    readonly DatabaseContext db;

    public TaxService(DatabaseContext database)
    {
        db = database;
    }

    public async Task<string> DeleteAsync(int? id)
    {
        if (await db.Taxes.FindAsync(id) is Tax tax)
        {
            string title = tax.Name;

            db.Taxes.Remove(tax);

            try
            {
                await db.SaveChangesAsync();

                return title;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        return null;
    }

    public async Task<List<Tax>> GetAllAsync()
    {
        return await db.Taxes.AsNoTracking().ToListAsync();
    }
}

To e.g:

public class TaxService<T> where T : Tax
{
    readonly DatabaseContext db;

    DbSet<Tax> dbSet => db.Tax;

    public TaxService(DatabaseContext database)
    {
        db = database;
    }

    public async Task<string> DeleteAsync(int? id)
    {
        if (await dbSet.FindAsync(id) is T tax)
        {
            string title = tax.Name;

            dbSet.Remove(tax);

            try
            {
                await db.SaveChangesAsync();

                return title;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        return null;
    }

    public async Task<List<T>> GetAllAsync()
    {
        return await dbSet.AsNoTracking().OfType<T>().ToListAsync();
    }
}

Ofc there is issue in design above. When I try to call TaxService I have to pass Tax class via generic type => TaxService<Tax>

Also in method GetAllAsync I have to use OfType method to avoid compiler errors. Its not possible to return List<Tax> as List<T>

Any suggestions to design pattern? Thanks

Aucun commentaire:

Enregistrer un commentaire