Interface of Interface<T> using C#

本文关键字:Interface using gt of lt | 更新日期: 2023-09-27 18:14:48

我不知道下面的内容是否奇怪,但实际上需要一个接口的接口,以便将其存储在List中,而无需指定具体的实现。

的例子:

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();
}

你可以建议我做那件事的更好方法。这是我唯一想做的……

编辑

我不能提供一个非通用的接口,因为我是这样使用它的:

public class GenericRepository<T> : IRepository<T>
{
    ...generic repository methods...
}
//Specific repository...
public class MyTableClassRepository<MyTable> : GenericRepository<MyTable>
{
    public MyTableClassRepository(Database context) : base(context)
    {
    }
}

Interface of Interface<T> using C#

考虑以下设计

public interface IUnitOfWork : IDisposable
{
    T GetRepository<T>() where T : class;
    void SaveChanges();
}

在UnitOfWork的实现中,你可以使用IoC容器(在下面的例子中是Autofac)

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();
    }
}