Проблема вызова метода общего общего репозитория - PullRequest
0 голосов
/ 13 апреля 2019

У меня есть базовая настройка хранилища. Я хочу создать общий общий репозиторий для использования общего метода, который возвращает логическое значение с именем:

DoesRecordExist ()

У меня есть базовое репо и настройка общего репо, но у меня проблема со ссылкой на ICommonRepository в сервисе. Как мне вызвать этот метод?

BaseRepository:

   public abstract class BaseRepository<TModel> : IBaseRepository<TModel> where TModel : BaseClass
    {
        private readonly IDbContext _context;
        private readonly IValidator<TModel> _validator;

        public BaseRepository(IDbContext context, IValidator<TModel> validator = null)
        {
            _context = context;
            _validator = validator ?? new InlineValidator<TModel>();
        }

        public bool DoesRecordExist(Guid id)
        {
            return _context.Set<TModel>().Any(x => x.Guid == id);
        }
    }

CommonRepository:

 public  class CommonRepository<TModel> : BaseRepository<TModel> where TModel : BaseClass, ICommonRepository<TModel>
{
    private readonly IDbContext _context;
    private readonly IValidator<TModel> _validator;
    public CommonRepository(IDbContext context, IValidator<TModel> validator = null) : base(context, validator)
    {
        _context = context;
        _validator = validator ?? new InlineValidator<TModel>();
    }
    public bool CommonDoesRecordExist(Guid id)
    {
        return DoesRecordExist(id);
    }
}

GlobalService:

private readonly ICategoryRepository _categoryRepository;
private readonly ISubcategoryRepository _subCategoryRepository;
private readonly ISubcategoryDescriptionRepository _subcategoryDescriptionRepository;
private readonly ICommonRepository<??????> _commonRepository;

public GlobalDataService(
    ICategoryRepository categoryRepository, 
    ISubcategoryRepository subCategoryRepository, 
    ISubcategoryDescriptionRepository subcategoryDescriptionRepository, 
    ICommonRepository<????> commonRepository)
{
    _categoryRepository = categoryRepository;
    _subCategoryRepository = subCategoryRepository;
    _subcategoryDescriptionRepository = subcategoryDescriptionRepository;
    _commonRepository = commonRepository;
}

 public bool DoesUserRecordExist(Guid userId)
    {
        //PROBLEM ON THIS LINE... bool existingData = _commonRepository.CommonDoesRecordExist(userId); 
            if (existingData)
            {
                //do stuff
            }
            else
            {
                //do other stuff
            }
        }

ICommonRepository.cs

   public interface ICommonRepository<T> : IBaseRepository
    {
        bool CommonDoesRecordExist(Guid id);
    }

IBaseRepository.cs

public interface IBaseRepository<T> : IBaseRepository
{
    bool DeleteAll();
    bool DoesRecordExist(Guid id, Expression<Func<T, bool>> filter);
    List<T> GetAll();
    T GetOne(Guid id);
    T Save(T item);
    bool Delete(Guid id);
    bool Delete(T item);
    IQueryable<T> Include(params Expression<Func<T, object>>[] includes);

}

public interface IBaseRepository
{
    string CollectionName { get; }
}

Ответы [ 2 ]

1 голос
/ 15 апреля 2019

Затем вам понадобится фабрика, у которой есть общий способ получить желаемый репозиторий

public interface ICommonProvider {
    ICommonRepository<T> GetRepository<T>();
}

public class CommonProvider : ICommonProvider {
    private readonly ILifetimeScope lifetimeScope;

    public CommonProvider(ILifetimeScope lifetimeScope) {
        this.lifetimeScope = lifetimeScope;
    }

    public ICommonRepository<T> GetRepository<T>() {
        return lifetimeScope.Resolve<ICommonRepository<T>>();
    }
}

, зарегистрированное при запуске

builder.RegisterType<CommonProvider>().As<ICommonProvider>();

и введите это в службу

//...removed for brevity

private readonly ICommonProvider commonProvider;

public GlobalDataService(
    ICategoryRepository categoryRepository, 
    ISubcategoryRepository subCategoryRepository, 
    ISubcategoryDescriptionRepository subcategoryDescriptionRepository, 
    ICommonProvider commonProvider) {

    //...removed for brevity

    this.commonProvider = commonProvider;
}

public bool DoesUserRecordExist(Guid userId) {
    ICommonRepository<User> repository = commonProvider.GetRepository<User>();
    var existingData = repository.CommonDoesRecordExist(userId);
    if (existingData) {
        //do stuff
    } else {
        //do other stuff
    }
}

//...

Тем не менее, я бы предложил отойти от глобальной службы данных и следовать явному принципу зависимости в более твердом подходе.

Простой пример

public class UserService {
    private ICommonRepository<User> repository;

    public UserService(ICommonRepository<User> repository) {
        this.repository = repository;
    }

    public bool DoesUserRecordExist(Guid userId) {
        var existingData = repository.DoesRecordExist(userId);
        if (existingData) {
            //do stuff
        } else {
            //do other stuff
        }
    }        
}

и зарегистрирован в вашем DI-контейнере что-то вроде

builder.RegisterGeneric(typeof(CommonRepository<>))
    .As(typeof(ICommonRepository<>))
    .InstancePerLifetimeScope();

Ссылка Autofac: концепции регистрации - открытые общие компоненты

0 голосов
/ 13 апреля 2019

Вы не можете напрямую вызывать метод дочернего класса, используя ссылку на родительский класс.Вам нужно разыграть _commonRepository до CommonRepository.

Однако, если CommonDoesRecordExist возвращает только DoesRecordExist, то почему бы вам просто не позвонить DoesRecordExist напрямую.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...