如何设置使用通用存储库的.net核心服务

时间:2019-10-21 16:29:12

标签: c# asp.net-core dependency-injection

我正在使用.netcore 3.0构建通用数据存储库。使用EF Core。我该如何在不需要提供实际实体名称的地方设置服务,例如:

services.AddScoped<RepositoryBase<Feature>>(); 

有没有一种方法可以配置所有这些选项?

这些主要是CRUD操作。

通用存储库

namespace CoreAPI1.Data.Services
{

    public class RepositoryBase<TEntity>  where TEntity : class
    {
        private readonly DbContext _context;
        private readonly DbSet<TEntity> _dbSet;

        public RepositoryBase(DbContext context)
        {
            _context = context;
            if (_context == null)
                throw new ArgumentNullException();

            _dbSet = context.Set<TEntity>();
        }

        public async Task<IEnumerable<TEntity>> GetAll()
        {
            return _dbSet.AsNoTracking().ToList();
        }
    }
}

服务

public static void  ConfigureServices(IServiceCollection services)
{

    services.AddDbContext<TruckContext>(ServiceLifetime.Scoped);
    services.AddScoped<IFileService, FileService>();
    services.AddScoped<IImageRepository, ImageRepository>();
    services.AddScoped<RepositoryBase<Feature>>();
    services.AddControllers();
   // services.AddAutoMapper(typeof(Truck));
    services.AddMvc(_x=>_x.EnableEndpointRouting = 
     false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

}

呼叫控制者

namespace CoreAPI1.Data.Controllers
{
    [Route("api/features")]
    [ApiController]
    public class FeaturesController :ControllerBase
    {
        private RepositoryBase<Data.Entities.Feature> _repository;
        private IMapper _mapper;

        public FeaturesController(RepositoryBase<Data.Entities.Feature> repository, IMapper mapper)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(_repository));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));

        }

        [HttpGet]
        public async Task<IEnumerable<Domain.Models.Feature>> GetFeatures()
        {

            var _features = await _repository.GetAllAsync();
            List<Domain.Models.Feature> _returnedFeatures = new List<Domain.Models.Feature>();


            try
            {
                foreach (var f in _features)
                {
                    var _returnedFeature = _mapper.Map<Domain.Models.Feature>(f);
                    _returnedFeatures.Add(_returnedFeature);
                }
                return _returnedFeatures;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());

            }

        }
    }
}

2 个答案:

答案 0 :(得分:2)

如果您要谈论的是,则可以通用地注册类型:

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

例如,这将为Repository<Foo>注入IRespository<Foo>

答案 1 :(得分:0)

包装DbContext并创建存储库的实现工作单元类。