Reputation: 5684
I don't know if the following is weird but actually need an interface for an interface< T > in order to store it in a List without specify a specific implementation.
Example:
public interface IRepository<T>
{
void Add(T newEntity);
void Remove(T entity);
IEnumerable<T> FindAll();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}
public interface IUnitOfWork
{
//Here i would like to store just a IRepository without implementation
IList<IRepository<**I have to specify implementation here**>> Repositories { get; set; }
bool Commit();
}
You are free to suggest me better ways to do that. This is only what i have though to do...
EDIT
I cannot provide a non-generic interface because i'm using it like this:
public class GenericRepository<T> : IRepository<T>
{
...generic repository methods...
}
//Specific repository...
public class MyTableClassRepository<MyTable> : GenericRepository<MyTable>
{
public MyTableClassRepository(Database context) : base(context)
{
}
}
Upvotes: 4
Views: 182
Reputation: 1728
Consider the following design
public interface IUnitOfWork : IDisposable
{
T GetRepository<T>() where T : class;
void SaveChanges();
}
In the implementation of the UnitOfWork you can use IoC container (Autofac in the example below)
public class UnitOfWork : IUnitOfWork
{
private static IContainer _container;
Hashtable _repositories = new Hashtable();
public static Module CurrentRepositoriesModule { get; set; }
public UnitOfWork()
{
var builder = new ContainerBuilder();
if (CurrentRepositoriesModule != null)
builder.RegisterModule(CurrentRepositoriesModule);
_container = builder.Build();
}
public T GetRepository<T>() where T : class
{
var targetType = typeof(T);
if (!_repositories.ContainsKey(targetType))
{
_repositories.Add(targetType, _container.Resolve<T>());
}
return (T)_repositories[targetType];
}
public void SaveChanges()
{
throw new NotImplementedException();
}
}
Upvotes: 3