分享基於EF6、Unitwork、Autofac的Repository模式設計

来源:https://www.cnblogs.com/Run2948/archive/2019/07/19/11212770.html
-Advertisement-
Play Games

分享基於EF6、Unitwork、Autofac的Repository模式設計 [TOC] 一、實現的思路和結構圖 Repository的共同性 有一些公共的方法(增刪改查), 這些方法無關於Repository操作的是哪個實體類,可以把這些方法定義成介面IRepository,然後有個基類Base ...


目錄

分享基於EF6、Unitwork、Autofac的Repository模式設計

一、實現的思路和結構圖

  • Repository的共同性

有一些公共的方法(增刪改查), 這些方法無關於Repository操作的是哪個實體類,可以把這些方法定義成介面IRepository

  • Repository的差異性

每個Repository類又會有一些差異性,應當允許它們能夠繼承BaseRepository

  • Repository的協同性

    不同的Repository可能需要協同,Repository對數據的修改,需要在統一的保存.
    最終實現的類結構圖如下:

類結構圖

二、Repository設計具體的實現代碼

IRepository

  • 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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • JVM中(留神:馬上講到的這兩個存儲區只在JVM內部與物理存儲區無關)存在一個主記憶體(Main Memory),Java中所有的變數存儲在主記憶體中,所有實例和實例的欄位都在此區域,對於所有的線程是共用的(相當於黑板,其他人都可以看到的)。每個線程都有自己的工作記憶體(Working Memory),工 ...
  • 元組是一個不可修改的有序序列 格式:tuple_name = (元素1,元素2,元素3,...) ...
  • 這位大佬寫的不錯,每次不會都會去看看https://www.cnblogs.com/shenlanzhizun/p/6027042.html 另外補充一些Java8騷操作 BigDecimal求和 博客中位置:3.2 歸約:reduce(其實已經有了int類型的求和,我寫個這個類型的吧) 另外提一點 ...
  • 多數耗時操作可以非同步執行,推薦async/await。 但和UI相關的部分僅能在UI線程執行,這時UI線程的耗時操作,導致界面卡死,不夠友好。 我們可以創建一個單獨的UI線程顯示一個正在載入的視窗,可以在視窗顯示一些動畫之類的。 如果是WinForms那麼很容易做到。 WPF沒有提供這樣簡單的方式, ...
  • 根據市場需求,基於.NET CORE平臺開發的RoadFlow工作流平臺需要實現多語言版本。經過方案討論和比對,決定採用.NET自帶的本地化功能來實現多語言。話不多說,直接上實現方式。 首先修改Startup.cs 在public void ConfigureServices(IServiceCol ...
  • 首次使用C#編寫與COM口有關的程式,期間遇到了很多問題,寫下自己的經驗總結,如有錯漏,歡迎批評指正! 1、新建一個串口類( SerialPort類) 2、串口埠號搜索: 3、讀數據、顯示數據: 4、寫數據: 5、常用的埠設置和方法: 串口最基本的功能就是實現通信,簡單來說就是讀和寫,就像大家熟 ...
  • Hi、大家好,今天又是美好的一天。 關於 Settings Sync 擴展: Settings Sync可以同步你當前的VSCode配置環境,當你需要在其它的電腦工作時,您不用重頭再來一遍。新機器登錄一下就搞定了。再也不用折騰環境了。 大致原理:使用GitHub Gist來同步多台電腦上的設置,代 ...
  • ASP.NET MVC 分頁使用的是作者楊濤的MvcPager分頁控制項 地址:http://www.webdiyer.com/mvcpager/demos/ajaxpaging/ 這個分頁控制項在裡面有很好的的案例,及註意事項 分頁在我們的項目中是經常需要使用到的,普通分頁體驗是在是太差了,每一次點擊 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...