我在实施通用存储库时遇到问题

时间:2019-05-19 10:43:01

标签: c# generics design-patterns repository

我想构建通用存储库以使其易于实现。现在,我想在我的域服务中创建用于在依赖项注入中使用它的接口,但我不能

我想构建通用存储库以使其易于实现。我创建了获取实体及其上下文的通用抽象存储库。现在,我想在我的域服务中创建接口以在依赖注入中使用它

我的通用存储库:

 public abstract class Repository<T,K>:IRepository<T,K>
    {
        private Type t;
        private K _Context;
        private bool disposed = false;
        public Repository(K Context)
        {
            _Context = Context;
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _Context.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void Delete(object id)
        {
            T t = _Context.Set<T>().Find(id);
            _Context.Set<T>().Remove(t);
        }

        public T Get(object id)
        {
            return _Context.Set<T>().Find(id);
        }

        public IEnumerable<T> getList()
        {
            return _Context.Set<T>().ToList();
        }

        public void insert(T t)
        {
            _Context.Set<T>().Add(t);
        }

        public void Save()
        {
            _Context.SaveChanges();
        }

        public  void Update(T t)
        {
            _Context.Entry(t).State = EntityState.Modified;
        }
    }
}

我的存储库界面:

    public interface IRepository<T,K> where T : BaseEntity where K : BaseContext<K>
    {
        T Get(object id);
        IEnumerable<T> getList();
        void insert(T t);
        void Delete(object id);
        void Update(T t);
        void Save();

    }

我的错误是"the Type 'T' can not be used as type parameter 'T' in the generic type....The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IRepository'. There is no boxing conversion or type parameter conversion from 'T' to 'DomainModel.BaseEntity",我想知道如何解决此问题

1 个答案:

答案 0 :(得分:2)

您还必须将 where 约束放在类存储库 上,即:

const connection = new signalR.HubConnectionBuilder()
              .withUrl("http://www.coolurl.com/realtime")
              .configureLogging(signalR.LogLevel.Information)
              .build();
let response = await connection.invoke("POST", "/api/things", JSON.stringify({jsonBody: "payload"}))

这是因为C#对 Repository 中的T一无所知,但是它需要满足 IRepository where 标准, K>