0

I'm trying to create a database with translation tables for multiple languages and in order to have reusable components, I create abstract classes and interfaces for my entities. I am using dependency injection for DBContext in an abstract classe that implements an interface.

This is the class that needs the DB Context DI:

   public abstract class EntityWithTranslatableFieldsRepository<TEntity, TTranslatableDetails, TTranslatedEntity> :
    IEntityWithTranslatableFieldsRepository<TEntity, TTranslatableDetails, TTranslatedEntity>
    where TEntity : EntityWithTranslatableDetails<TTranslatedEntity, TTranslatableDetails>
    where TTranslatableDetails : TranslatableDetailss
{

    public EntityWithTranslatableFieldsRepository()
    {

    }
    private readonly DataContext _context;

    public EntityWithTranslatableFieldsRepository(DataContext context)
    {
        _context = context;
    }
    public TTranslatedEntity Get(int id, string language)
    {
        var entity = _context.Set<TEntity>().Find(id);
        _context.Entry(entity).Collection(c => c.TranslatableDetails).Load();
        return entity.GetTranslatedEntity(language);
    }

    public IEnumerable<TTranslatedEntity> GetAll(string language)
    {
        return _context.Set<TEntity>().Include(c => c.TranslatableDetails).ToList().Select(c => c.GetTranslatedEntity(language));
    }

}

Then I inherit the EntityWithTranslatableFieldsRepository

    public class CarService : EntityWithTranslatableFieldsRepository<Car, CarTranslatableDetails, GetCarDTO>
{
}

and then use DI again to inject it into a controller

    public class CarController : ControllerBase
{
    private readonly IEntityWithTranslatableFieldsRepository<Car, CarTranslatableDetails, GetCarDTO> _carService;

    public CarController(IEntityWithTranslatableFieldsRepository<Car,CarTranslatableDetails,GetCarDTO> carService)
    {
        _carService = carService;
    }


    [HttpGet("GetACar")]
    public ActionResult<GetCarDTO> GetACar(int id, string language)
    {
        return Ok(_carService.Get(id, language));
    }


    [HttpGet("GetAllCars")]
    public ActionResult<IEnumerable<GetCarDTO>> GetAllCars(string language)
    {
        return Ok(_carService.GetAll(language));
    }

}

I register the DI in Project.cs looks like this:

builder.Services.AddSingleton<IEntityWithTranslatableFieldsRepository<Car, CarTranslatableDetails, GetCarDTO>, CarService>();

When I run Swagger and try to get data I run into the error:

System.NullReferenceException: Object reference not set to an instance of an object.

which points to

var entity = _context.Set<TEntity>().Find(id);
Ibrahim
  • 131
  • 2
  • 12

0 Answers0