您的位置:首页 > 编程语言 > ASP

Asp.Net Core 2.0 之旅---AutoFac 仓储泛型的依赖注入

2017-12-30 14:42 1806 查看
在上节的博客中AutoFac IOC容器的使用教程的结尾出提到在下一节会详细讲解仓储泛型的依赖注入。将会在本次的文章通过详细的例子来演示。

1、为何需要仓储的泛型注入?

首先我先放一段代码:

public class ShareYunSourseAppService :IShareYunSourseAppService
{
private readonly IRepository<YunSourse> _yunsourseIRepository;
public ShareYunSourseAppService(IRepository<YunSourse> yunsourseIRepository)
{
_yunsourseIRepository = yunsourseIRepository;
}
public async Task GetName()
{
var list = _yunsourseIRepository.GetAll().Where(m=>!string.IsNullOrEmpty(m.Content)).ToList();

}
}


从上面的代码我们可以看出,对一个实体仓储的依赖注入 是多么的简洁。相信有人为了获取一个实体的仓储去新建一个仓储接口,然后新建其实现类并继承了仓储基类。一个实体也还好,如果10呢,100个呢,其中的重复工作是不是特别巨大呢?为了提高我们开发人员的工作效率。这个文章就孕育而生啦。在此我一步步介绍如何实现仓储泛型的依赖注入!

2、定义仓储接口   IRepository

/// <summary>
/// 泛型仓储接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRepository<T> where T : Entity
{
/// <summary>
/// IQueryable to be used to select entities from database
/// </summary>
/// <returns></returns>
IQueryable<T> GetAll();
/// <summary>
/// 用来获取所有实体
/// </summary>
/// <returns>所有实体的List集合</returns>
List<T> GetAllList();
/// <summary>
///  用来获取所有实体
/// </summary>
/// <returns>所有实体的List集合</returns>
Task<List<T>> GetAllListAsync();
/// <summary>
/// 基于提供的表达式 获取所有实体
/// </summary>
/// <param name="predicate">所有实体的List集合</param>
/// <returns></returns>
List<T> GetAllList(Expression<Func<T,bool>> predicate);

/// <summary>
/// 泛型方法,通过id获取实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T GetById(object id);

/// <summary>
/// 泛型方法--添加实体
/// </summary>
/// <param name="model"></param>
void Insert(T model);

/// <summary>
/// 泛型方法,更新实体
/// </summary>
/// <param name="model"></param>
void Update(T model);

/// <summary>
/// 泛型方法--删除实体
/// </summary>
/// <param name="model"></param>
void Delete(T model);

/// <summary>
/// 只读Table
/// </summary>
IQueryable<T> Table { get; }
}


仓储接口 IRepository 的泛型类型 必须是 Entity 类型的。

/// <summary>
/// 泛型实体基类
/// </summary>
/// <typeparam name="TPrimaryKey">主键类型</typeparam>
public abstract class Entity<TPrimaryKey>
{
/// <summary>
/// 主键
/// </summary>
public virtual TPrimaryKey Id { get; set; }
}

/// <summary>
/// 定义默认主键类型为int的实体基类
/// </summary>
public abstract class Entity : Entity<int>
{

}


2、实现其仓储 接口 

/// <summary>
/// 泛型仓储类,实现泛型仓储接口。
/// </summary>
/// <typeparam name="T"></typeparam>
public class EfRepositoryBase<T> : IRepository<T> where T : Entity  //约束在最后面。
{
private readonly YunSourseMySqlContext _context;
private DbSet<T> _entities;

/// <summary>
///
/// </summary>
public EfRepositoryBase(YunSourseMySqlContext context)
{
_context = context;
}

public IQueryable<T> GetAll()
{
return Table;
}
public  List<T> GetAllList()
{
return  GetAll().ToList();
}
public  List<T> GetAllList(Expression<Func<T, bool>> predicate)
{
return  GetAll().Where(predicate).ToList();
}
public  async Task<List<T>> GetAllListAsync()
{
return await GetAll().ToListAsync();
}

public  async Task<List<T>> GetAllListAsync(Expression<Func<T, bool>> predicate)
{
return await GetAll().Where(predicate).ToListAsync();
}
public DbSet<T> Entities
{
get
{
if (_entities == null)
{
_entities = _context.Set<T>();
}
return _entities;
}
}

/// <summary>
/// 实现泛型接口中的IQueryable<T>类型的 Table属性
/// 标记为virtual是为了可以重写它
/// </summary>
public virtual IQueryable<T> Table
{
get
{
return this.Entities;
}

}

public T GetById(object id)
{
return this.Entities.Find(id);
}

public void Insert(T model)
{
try
{
if (model == null)
{
throw new ArgumentNullException("model");
}
else
{
this.Entities.Add(model);
this._context.SaveChanges();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public void Update(T model)
{
try
{
//model为空,抛空异常
if (model == null)
{
throw new ArgumentNullException("model");
}
else
{
//直接保存了
this._context.SaveChanges();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public void Delete(T model)
{
try
{
if (model == null)
{
throw new ArgumentNullException("entity");
}
this.Entities.Remove(model);
this._context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}


EfRepositoryBase 是IRepository 的实现  其泛型类型 同样要是Entity类型。

3、仓储接口 和仓储实现类  完成以后 就需要 进行仓储的泛型的依赖注入了。

在 Web项目中的 Statrup启动类中的ConfigureServices方法中

builder.RegisterGeneric(typeof(EfRepositoryBase<>)).As(typeof(IRepository<>)).InstancePerDependency();//注册仓储泛型
InstancePerDependency//每次调用,都会重新实例化对象;每次请求都创建一个新的对象;

4、至此恭喜你,你已经完成了仓储泛型的依赖注入,就可以用开篇展示的通过构造方法依赖注入的方式 实例化 仓储泛型。注意的是,定义的实体 一定要继承 Entity!

5、不足之处:没有展示 事务。可能在以后的学习中发表出来。

结束语:仓储的方法 我是汲取了ABP框架的部分 方法。可以自行拓展。下次准备分享的是MiniProfiler,感兴趣的小伙伴可以自行搜索。

欢迎 讨论,共同学习。。。。。。。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: