My Problem is from here,
I have written an Interface for country repository and I am following generic repository with UnitOfWork, I am also using ninject for DI
public interface ICountryRepository : IRepository<Country>
{
List<Country> GetAll();
}
Implemented country repository interface,
public class CountryRepository : BaseRepository<Country>, ICountryRepository
{
public CountryRepository(DbContextcontext) : base(context)
{
}
public List<Country> GetAll(){
// Not implemented
}
}
There is a additional method in ICountryRepository interface and I have implemented it too. But when I need that method to use using UnitOfWork, I can't use that method. That is giving System.NullReferenceException
I have tried,
ICountryRepository repository = UnitOfWork.Repository<Country>() as ICountryRepository;
return repository.GetAll();
The downcasting suggest the method but without casting the method is not accessible.
Additional Codes are given,
Entities
Base Entity
public class BaseEntity
{
public int Id { get; set; }
}
Product Entity
public class Country : BaseEntity
{
public string Name { get; set; }
}
Repositories
Interface
public interface IRepository<T>
{
void Add(T entity);
}
Base Repository
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
protected IDbContext _context;
private readonly IDbSet<TEntity> _dbEntitySet;
private bool _disposed;
public BaseRepository(IDbContext context)
{
_context = context;
_dbEntitySet = _context.Set<TEntity>();
}
public void Add(TEntity entity)
{
_context.SetAsAdded(entity);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
_context.Dispose();
}
_disposed = true;
}
}
Unit Of Work
Interface
public interface IUnitOfWork : IDisposable
{
IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity;
void BeginTransaction();
int Commit();
Task<int> CommitAsync();
void Rollback();
void Dispose(bool disposing);
}
Unit of work implemented
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContext _context;
private bool _disposed;
private Hashtable _repositories;
public UnitOfWork(IDbContext context)
{
_context = context;
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
{
if (_repositories == null)
{
_repositories = new Hashtable();
}
var type = typeof(TEntity).Name;
if (_repositories.ContainsKey(type))
{
return (IRepository<TEntity>)_repositories[type];
}
var repositoryType = typeof(BaseRepository<>);
_repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
return (IRepository<TEntity>)_repositories[type];
}
/* Other Implementation
*
*
*
*/
}