ASP.Net Core基于EF6、Unitwork、Autofac实现Repository模式

一、实现的思路和结构图

  • Repository的共同性

有一些公共的方法(增删改查), 这些方法无关于Repository操作的是哪个实体类,可以把这些方法定义成接口IRepository,然后有个基类BaseRepository实现该接口的方法。常见的方法,比如Find, Filter, Delete, Create等

  • Repository的差异性

每个Repository类又会有一些差异性,应当允许它们能够继承BaseRepository之外,还能够再扩展自己的一些方法。所以每个类都可以再定义一个自己特有的接口,定义一些属于自己Repository的方法。

  • Repository的协同性

不同的Repository可能需要协同,Repository对数据的修改,需要在统一的保存.
最终实现的类结构图如下:

二、Repository设计具体的实现代码

IRepository接口定义了Repository共有的方法, BaseRepository实现了这些接口的方法。其它的Repository类再集成BaseRepository方法,就天然的得到了对数据操作的基本方法。

  • IRepository代码
    public interface IRepository<TEntity> where TEntity : class
    {
        /// <summary>
        /// Gets all objects from database
        /// </summary>
        /// <returns></returns>
        IQueryable<TEntity> All();

        /// <summary>
        /// Gets objects from database by filter.
        /// </summary>
        /// <param name="predicate">Specified a filter</param>
        /// <returns></returns>
        IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate);

        /// <summary>
        /// Gets objects from database with filtering and paging.
        /// </summary>
        /// <param name="filter">Specified a filter</param>
        /// <param name="total">Returns the total records count of the filter.</param>
        /// <param name="index">Specified the page index.</param>
        /// <param name="size">Specified the page size</param>
        /// <returns></returns>
        IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> filter, out int total, int index = 0, int size = 50);

        /// <summary>
        /// Gets the object(s) is exists in database by specified filter.
        /// </summary>
        /// <param name="predicate">Specified the filter expression</param>
        /// <returns></returns>
        bool Contains(Expression<Func<TEntity, bool>> predicate);

        /// <summary>
        /// Find object by keys.
        /// </summary>
        /// <param name="keys">Specified the search keys.</param>
        /// <returns></returns>
        TEntity Find(params object[] keys);

        /// <summary>
        /// Find object by specified expression.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        TEntity Find(Expression<Func<TEntity, bool>> predicate);

        /// <summary>
        /// Create a new object to database.
        /// </summary>
        /// <param name="t">Specified a new object to create.</param>
        /// <returns></returns>
        void Create(TEntity t);

        /// <summary>
        /// Delete the object from database.
        /// </summary>
        /// <param name="t">Specified a existing object to delete.</param>
        void Delete(TEntity t);

        /// <summary>
        /// Delete objects from database by specified filter expression.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        int Delete(Expression<Func<TEntity, bool>> predicate);

        /// <summary>
        /// Update object changes and save to database.
        /// </summary>
        /// <param name="t">Specified the object to save.</param>
        /// <returns></returns>
        void Update(TEntity t);

        /// <summary>
        /// Select Single Item by specified expression.
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        TEntity FirstOrDefault(Expression<Func<TEntity, bool>> expression);
    }
  • BaseRepository代码
    public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        protected readonly DbContext Context;

        public BaseRepository(DbContext context)
        {
            Context = context;
        }

        /// <summary>
        /// Gets all objects from database
        /// </summary>
        /// <returns></returns>
        public IQueryable<TEntity> All()
        {
            return Context.Set<TEntity>().AsQueryable();
        }

        /// <summary>
        /// Gets objects from database by filter.
        /// </summary>
        /// <param name="predicate">Specified a filter</param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> predicate)
        {
            return Context.Set<TEntity>().Where<TEntity>(predicate).AsQueryable<TEntity>();
        }

        /// <summary>
        /// Gets objects from database with filtering and paging.
        /// </summary>
        /// <param name="filter">Specified a filter</param>
        /// <param name="total">Returns the total records count of the filter.</param>
        /// <param name="index">Specified the page index.</param>
        /// <param name="size">Specified the page size</param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> Filter(Expression<Func<TEntity, bool>> filter, out int total, int index = 0,
            int size = 50)
        {
            var skipCount = index * size;
            var resetSet = filter != null
                ? Context.Set<TEntity>().Where<TEntity>(filter).AsQueryable()
                : Context.Set<TEntity>().AsQueryable();
            resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            total = resetSet.Count();
            return resetSet.AsQueryable();
        }

        /// <summary>
        /// Gets the object(s) is exists in database by specified filter.
        /// </summary>
        /// <param name="predicate">Specified the filter expression</param>
        /// <returns></returns>
        public bool Contains(Expression<Func<TEntity, bool>> predicate)
        {
            return Context.Set<TEntity>().Any(predicate);
        }

        /// <summary>
        /// Find object by keys.
        /// </summary>
        /// <param name="keys">Specified the search keys.</param>
        /// <returns></returns>
        public virtual TEntity Find(params object[] keys)
        {
            return Context.Set<TEntity>().Find(keys);
        }

        /// <summary>
        /// Find object by specified expression.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual TEntity Find(Expression<Func<TEntity, bool>> predicate)
        {
            return Context.Set<TEntity>().FirstOrDefault<TEntity>(predicate);
        }

        /// <summary>
        /// Create a new object to database.
        /// </summary>
        /// <param name="t">Specified a new object to create.</param>
        /// <returns></returns>
        public virtual void Create(TEntity t)
        {
            Context.Set<TEntity>().Add(t);
        }

        /// <summary>
        /// Delete the object from database.
        /// </summary>
        /// <param name="t">Specified a existing object to delete.</param>
        public virtual void Delete(TEntity t)
        {
            Context.Set<TEntity>().Remove(t);
        }

        /// <summary>
        /// Delete objects from database by specified filter expression.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual int Delete(Expression<Func<TEntity, bool>> predicate)
        {
            var objects = Filter(predicate);
            foreach (var obj in objects)
                Context.Set<TEntity>().Remove(obj);
            return Context.SaveChanges();
        }

        /// <summary>
        /// Update object changes and save to database.
        /// </summary>
        /// <param name="t">Specified the object to save.</param>
        /// <returns></returns>
        public virtual void Update(TEntity t)
        {
            try
            {
                var entry = Context.Entry(t);
                Context.Set<TEntity>().Attach(t);
                entry.State = EntityState.Modified;
            }
            catch (OptimisticConcurrencyException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Select Single Item by specified expression.
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> expression)
        {
            return All().FirstOrDefault(expression);
        }
    }

IUnitOfWork接口定义了方法获取特定的Repository, 执行存储过程, SaveChange方法提交修改,统一更新数据。

  • IUnitOfWork接口代码:
    public interface IUnitOfWork : IDisposable
    {
        DbContext DbContext { get; }
        TRepository GetRepository<TRepository>() where TRepository : class;
        void ExecuteProcedure(string procedureCommand, params object[] sqlParams);
        void ExecuteSql(string sql);
        List<T> SqlQuery<T>(string sql);
        void SaveChanges();
    }

UnitOfWork代码, 代码中使用到了Autofac中的IComponentContext来获取Repository实例

    public class UnitOfWork : IUnitOfWork
    {
        private readonly IComponentContext _componentContext;
        protected readonly DbContext Context;

        public UnitOfWork(DbContext context, IComponentContext componentContext)
        {
            Context = context;
            _componentContext = componentContext;
        }

        public DbContext DbContext => Context;

        public TRepository GetRepository<TRepository>() where TRepository : class
        {
            return _componentContext.Resolve<TRepository>();
        }

        public void ExecuteProcedure(string procedureCommand, params object[] sqlParams)
        {
            Context.Database.ExecuteSqlCommand(procedureCommand, sqlParams);
        }

        public void ExecuteSql(string sql)
        {
            Context.Database.ExecuteSqlCommand(sql);
        }

        public List<T> SqlQuery<T>(string sql)
        {
            return Context.Database.SqlQuery<T>(sql).ToList();
        }

        public void SaveChanges()
        {
            try
            {
                Context.SaveChanges();
            }
            catch (InvalidOperationException ex)
            {
                if (!ex.Message.Contains("The changes to the database were committed successfully"))
                {
                    throw;
                }
            }
        }

        public void Dispose()
        {
            Context?.Dispose();
        }
    }

三、Repository设计的具体的使用

这里我们定义一个IStudentRepository接口, 包含了方法GetAllStudents(), 同时继承于IRepository<Student>接口

public interface IStudentRepository : IRepository<Student>
{
    IEnumerable<dynamic> GetAllStudents();
}

接着定义StudentRepository类来实现这个接口

public class StudentRepository : BaseRepository<Student>, IStudentRepository
{
    private readonly SchoolContext _context;

    public StudentRepository(SchoolContext context)
        : base(context)
    {
        _context = context;
    }

    public IEnumerable<dynamic> GetAllStudents()
    {
        return _context.Students;
    }
}
  • Application_Start方法中使用Autofac注册Repository的代码如下:
    var builder = new ContainerBuilder();

    //register controllers
    builder.RegisterControllers(typeof(MvcApplication).Assembly);

    //register repository
    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();

    //add the Entity Framework context to make sure only one context per request
    builder.RegisterType<SchoolContext>().InstancePerRequest();
    builder.Register(c => c.Resolve<SchoolContext>()).As<DbContext>().InstancePerRequest();

    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  • 在控制器中注入使用Repository的代码如下:
private readonly IUnitOfWork _repositoryCenter;

private readonly IStudentRepository _studentRepository;

public HomeController(IUnitOfWork repositoryCenter)
{
    _repositoryCenter = repositoryCenter;
    _studentRepository = _repositoryCenter.GetRepository<IStudentRepository>();
}

public ActionResult Index(Student sessionStudent)
{
    var students = _studentRepository.GetAllStudents();

    // 同时你也可以使用定义于IRepository<Student>中的方法, 比如:

    _studentRepository.Delete(students.First());
    _repositoryCenter.SaveChanges();

    ...

    return View(students);
}

四、思路总结

上面的设计,把Repository的通用代码剥离到父类中,同时又允许每个Repository扩展自己的方法,达到了比较理想的状态。

只是现在的设计和Autofac耦合了,但是如果想继续剥离Autofac直接使用 _repositoryCenter.GetRepository<IStudentRepository>(); 的方式获取IStudentRepository的实例就很困难了。

五、案例源码

源代码仓库 AutoFacMvc

到此这篇关于ASP.Net Core基于EF6、Unitwork、Autofac实现Repository模式的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • .net6引入autofac框架

    引入NuGet 注册Autofac 在Program的var app = builder.Build():前加上这段代码 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterType<LogRecordsService>

  • NET Core 3.0 AutoFac内置DI替换的新姿势分享

    .NET Core 3.0 和 以往版本不同,替换AutoFac服务的方式有了一定的变化,在尝试着升级项目的时候出现了一些问题. 原来在NET Core 2.1时候,AutoFac返回一个 IServiceProvider 参数注入到ConfigureServices .NET Core 服务中,基本大痣是这样做的. 首先我们需要一个重写 Autofac.Module 的方法,这将用于将我们 Register [数据访问层] 以及 Services [逻辑层] 的注册. public class

  • C# 使用 Castle 实现 AOP及如何用 Autofac 集成 Castle

    Castle 是 2003 年诞生于 Apache Avalon 项目,目的是为了创建一个IOC 框架.发展到现在已经有四个组件: ORM组件:ActiveRecord IOC组件:Windsor 动态代理组件:DynamicProxy Web MVC组件:MonoRail 本文主要介绍 动态代理组件 Castle.DynamicProxy 基本用法 Castle.DynamicProxy 是通过 Emit 反射动态生成代理类来实现的,效率相对静态植入要慢一点,但比普通的反射又高一些.动态代理只

  • .Net Core 之AutoFac的使用

    目录 Autofac介绍 组件的三种注册方式 生命周期 AutoFac 在asp .net core中的使用 本文不介绍IoC和DI的概念,如果你对Ioc之前没有了解的话,建议先去搜索一下相关的资料 这篇文章将简单介绍一下AutoFac的基本使用以及在asp .net core中的应用 Autofac介绍 组件的三种注册方式 1.反射 2.现成的实例(new) 3.lambda表达式 (一个执行实例化对象的匿名方法) 下面是一些简短的示例,我尽可能多的列出来一些常用的注册方式,同时在注释中解释下

  • .NET中IoC框架Autofac用法讲解

    1 前置阅读 在阅读本文章之前,你可以先阅读: 什么是依赖注入 2 简介 Autofac与C#语言的结合非常紧密,并学习它非常的简单,也是.NET领域最为流行的IoC框架之一. 3 使用 首先,将Autofac的NuGet软件包安装到您的应用程序中. Autofac 然后,我们通过创建ContainerBuilder来注册组件. var builder = new ContainerBuilder(); builder.RegisterType<Knife>(); builder.Regist

  • 浅析依赖注入框架Autofac的使用

    下面通过代码给大家分享下依赖注入框架Autofac的使用,具体如下所示:  Autofac是一款IOC框架,比较于其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很轻量级性能上也是很高的. 1)解压它的压缩包,主要看到Autofac.dll,Autofac.Configuration.dll,这也是本篇文章重点使用的Autofac的类库. 2)创建一个控制台工程,并且引用以上的DLL文件.创建一个数据库操作接口IDatabase.cs: /// <summary

  • .NET Core使用Autofac容器的DI依赖注入,IOC控制反转及AOP切面编程

    目录 Autofac 容器 Autofac 多种注入方式 Autofac 生命周期 Autofac 支持配置文件 Autofac 整合 .NET 5 MVC Autofac 支持控制器属性注入 Autofac 单实例多实现 Autofac 支持 AOP Autofac 容器 Autofac 是一款.NET IoC 容器 . 它管理类之间的依赖关系, 从而使 应用在规模及复杂性增长的情况下依然可以轻易地修改 . 它的实现方式是将常规的.net类当做组件处理. 安装 NuGet 程序包: Autof

  • 谈一谈autofac组件的实例范围

    实例范围决定如何在请求之间共享服务. 原文地址:http://docs.autofac.org/en/latest/lifetime/instance-scope.html 每个依赖一个实例 使用这个选项,每次请求服务都会返回一个新实例.使用 InstancePerDependency() 指定.这是默认选项.下面的代码,第2行和第3行是等价的. var builder = new ContainerBuilder(); builder.RegisterType<Worker>(); buil

  • C# 利用Autofac批量接口注入依赖的问题小结

    背景: 本人在一位大佬的Colder框架中看到了这个接口注入,然后呢就想学习一下ioc思想与di设计模式.此写法给我的感觉就是 非常的 优雅 ,优雅永不过时.关于接口注入具体是什么可以最后推荐的地址.话不多说,开撸. 安装: 打开nuget管理工具,将我下面标红色的包都进行安装(注:千万别安装错了,按照名字不差的安装) 使用: 我们新建一个DI的文件夹,在文件夹中增加一个接口:IDependency.cs namespace Coldairarrow { /// <summary> /// 注

  • .Net Core中使用Autofac替换自带的DI容器的示例

    目录 项目创建 方案演示 .Net Core自带DI 不同的特性 批量注入 属性注入 存储并提取容器实例 为什么叫浅谈呢?就是字面上的意思,讲得比较浅,又不是不能用(这样是不对的)!!! Aufofac大家都不陌生了,说是.Net生态下最优秀的IOC框架那是一点都过分.用的人多了,使用教程也十分丰富,官网教程也比较详细(如果英文功底还不错的话). 那我为什么还要写这样一篇博客呢,一是用作学习笔记,二就是闲的. 废话不多说,开始正文 项目创建 云创建一个.Net Core Api项目,然后再添加一

随机推荐