ASP.NETCore使用AutoFac依賴注入

力軟資訊發表於2020-03-09

實現程式碼

1、新建介面類:IRepository.cs,規範各個操作類的都有那些方法,方便管理。

using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Text;namespace CMS.Entity.Interfaces
{    public  interface IRepository<T> where T:class
    {        /// <summary>
        /// 新增        /// </summary>
        /// <param name="entity">實體物件</param>
        void Add(T entity);        /// <summary>
        /// 更新        /// </summary>
        /// <param name="entity">實體物件</param>
        void Update(T entity);        /// <summary>
        /// 刪除        /// </summary>
        /// <param name="entity">實體物件</param>
        void Delete(T entity);        /// <summary>
        /// 刪除        /// </summary>
        /// <param name="where">條件(lambda表示式)</param>
        void Delete(Expression<Func<T, bool>> where);        /// <summary>
        /// 根據ID獲取一個物件        /// </summary>
        /// <param name="Id">主鍵ID</param>
        /// <returns>物件</returns>
        T GetById(long Id);        /// <summary>
        /// 根據ID獲取一個物件        /// </summary>
        /// <param name="Id">主鍵ID</param>
        /// <returns>物件</returns>
        T GetById(string Id);        /// <summary>
        /// 根據條件獲取一個物件        /// </summary>
        /// <param name="where">條件(lambda表示式)</param>
        /// <returns>物件</returns>
        T Get(Expression<Func<T, bool>> where);        /// <summary>
        /// 獲取所有資料        /// </summary>
        /// <returns>所有資料</returns>
        IQueryable<T> GetAll();        /// <summary>
        /// 根據條件獲取資料        /// </summary>
        /// <param name="where">條件(lambda表示式)</param>
        /// <returns>資料</returns>
        IQueryable<T> GetMany(Expression<Func<T, bool>> where);        /// <summary>
        /// 根據條件獲取記錄數        /// </summary>
        /// <param name="where">條件(lambda表示式)</param>
        /// <returns></returns>
        int GetCount(Expression<Func<T, bool>> where);        /// <summary>
        /// 關閉代理        /// </summary>
        void CloseProxy();        /// <summary>
        /// 開啟代理        /// </summary>
        void OpenProxy();        /// <summary>
        /// 是否有指定條件的元素        /// </summary>
        /// <param name="where">條件(lambda表示式)</param>
        /// <returns></returns>
        bool IsHasValue(Expression<Func<T, bool>> where);
    }
}

2、新建倉儲基礎操作類RepositoryBase.cs,注意要一一對應實現IRepositroy介面的方法

using System;using System.Collections.Generic;using System.Text;using System.Linq;namespace CMS.Entity.Interfaces
{    public abstract class BaseRepository<T>  where T: class
    {        private BcmfDBContext db;//資料庫上下文        public BaseRepository(BcmfDBContext _db) {
            db = _db;
        }        public virtual void Save()
        {
            db.SaveChanges();
        }        public  virtual  void Add(T entity)
        {
            db.Set<T>().Add(entity);
        }        public virtual void CloseProxy()
        {
            db.Database.CommitTransaction();
        }        public virtual void Delete(T entity)
        {
            db.Set<T>().Remove(entity);
        }        public virtual void Delete(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {            var dataList = db.Set<T>().Where(where).AsEnumerable();
            db.Set<T>().RemoveRange(dataList);
        }        public virtual T Get(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {           return db.Set<T>().FirstOrDefault(where);
        }        public virtual System.Linq.IQueryable<T> GetAll()
        {            return db.Set<T>();
        }        public virtual T GetById(long Id)
        {            return db.Set<T>().Find(Id);
        }        public virtual T GetById(string Id)
        {            return db.Set<T>().Find(Id);
        }        public virtual int GetCount(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {            return db.Set<T>().Count(where);
        }        public virtual System.Linq.IQueryable<T> GetMany(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {            return db.Set<T>().Where(where);
        }        public virtual bool IsHasValue(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {            return db.Set<T>().Any(where);
        }        public virtual void OpenProxy()
        {
            db.Database.BeginTransaction();
        }        public virtual void Update(T entity)
        {
            db.Set<T>().Attach(entity);
            db.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
        }
    }
}

3、新建倉儲類TUserRepository與TOperateLogRepository,TUserRepository用於操作使用者表,TOperateLogRepository用於操作使用者記錄表,對應的User類與OperateLog類根據專案需求自行建立

using System;using System.Collections.Generic;using System.Text;using CMS.Entity.Repository;using CMS.Entity.Entity;using Microsoft.EntityFrameworkCore;using System.Linq;using CMS.Entity.Interfaces;namespace CMS.Entity.Repository
{    public class TUserRepository :BaseRepository<User>,IUserRepository
    {        public TUserRepository(BcmfDBContext db) : base(db) { }
    }    public interface IUserRepository : IRepository<User> { }
}
using System;using System.Collections.Generic;using System.Text;using CMS.Entity.Repository;using CMS.Entity.Entity;using Microsoft.EntityFrameworkCore;using System.Linq;using CMS.Entity.Interfaces;namespace CMS.Entity.Repository
{    public class TOperateLogRepository : BaseRepository<OperateLog>, IOperateLogRepository
    {        public TOperateLogRepository(BcmfDBContext db) : base(db) { }
    }    public interface IOperateLogRepository : IRepository<OperateLog>
    {
    }
}

 

4、分別在UserController與OperateLogController控制器中的建構函式注入倉儲類

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using CMS.Entity;using CMS.Entity.Entity;using Newtonsoft.Json;using CMS.WebApi.Core;using Microsoft.EntityFrameworkCore.Query;using CMS.Entity.Repository;namespace CMS.WebApi.Controllers
{    /// <summary>
    /// 使用者中心    /// </summary>
    //[Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]    public class UsersController : ControllerBase
    {        private readonly IUserRepository userRepository;        public UsersController(IUserRepository _userRepository)
        {
            userRepository = _userRepository;
        }        /// <summary>
        /// 獲取使用者列表        /// </summary>
        /// <returns></returns>        [HttpGet]        public string Get()
        {            var userList= userRepository.GetAll().ToList();            return JsonConvert.SerializeObject(userList);
        }
    }
}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using CMS.Entity.Repository;using Newtonsoft.Json;namespace CMS.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]    public class OperateLogController : ControllerBase
    {        private readonly IOperateLogRepository operateLogRepository;        public OperateLogController(IOperateLogRepository _operateLogRepository)
        {
            operateLogRepository = _operateLogRepository;
        }
        [HttpGet]        public string Get()
        {            var result = operateLogRepository.GetMany(m=>m.ActionLogId<100);            return JsonConvert.SerializeObject(result);
        }
    }
}

5、完成上述操作後,執行獲取資料時會系統報錯,那是由於還沒將倉儲類注入到服務中,接下來就實現用AutoFac注入倉儲類到專案服務中

新增引用Autofac,Auto.Configuration,Autofac.Extensions.DependencyInjection到專案中

 

這裡貼出Nuget程式控制臺命令:

Install-Package Autofac -Version 4.9.2
Install-Package Autofac.Configuration -Version 4.1.0
Install-Package Autofac.Extensions.DependencyInjection -Version 4.4.0

6、開啟專案Startup.cs,找到ConfigureServices方法,將void改為IServiceProvider返回值,如下

 //先引用名稱空間
using Autofac;
using Autofac.Extensions.DependencyInjection;
            
             builder = 
         builder.RegisterAssemblyTypes(=> t.Name.EndsWith( container =

7、重新生成釋出專案,完成


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69965343/viewspace-2679242/,如需轉載,請註明出處,否則將追究法律責任。

相關文章