Why is it not possible to do this:
public static void Init<TEntity>(params TEntity[] repositories) where TEntity : Entity
{
foreach (TEntity item in repositories)
{
Repository<item> rep = new Repository<item>();
}
}
The above code won’t compile: Cannot resolve symbol item
Yet this works:
public static void Init<TEntity>(TEntity entity) where TEntity : Entity
{
Repository<TEntity> rep = new Repository<TEntity>();
}
EDIT
I’m editing the OP to give a bigger picture of the problem. We are experiencing some issues with the entity framework Db Context being spawned by multiple repositories. Currently we access the repositories like:
Repository<Product> rep = new Repository<Product>()
Repository<Account> rep = new Repository<Account>()
Since there’s a relationship between product and account EF will complain about objects being attached to a different context. So we are trying to resolve this issue by consolidating repository access into a Unit of Work pattern:
Here’s an example of what I’m trying to achieve:
public class UnitOfWork
{
protected List<Entity> Repositories = new List<Entity>();
private readonly DbContext _context;
protected UnitOfWork()
{
_context = new SqlDbContext();
}
public static UnitOfWork Init<TEntity>(params TEntity[] repositories) where TEntity : Entity
{
UnitOfWork uow = new UnitOfWork();
foreach (TEntity item in repositories)
{
Repository<item> rep = new Repository<item>();
uow.Repositories.Add(rep);
}
return uow;
}
public IRepository<T> GetRepository<T>() where T : Entity
{
return Repositories.OfType<T>().Single();
}
}
So we can access our repositories like:
GetRepository<Product>().GetById(1);
GetRepository<Account>().GetById(123434);
itemis an instance of a type, but you need a type parameter to create an instance of your genericRepository<T>class.