温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NETCore使用AutoFac依赖注入

发布时间:2020-08-16 21:52:19 来源:ITPUB博客 阅读:188 作者:力软信息 栏目:编程语言

实现代码

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到项目中

ASP.NETCore使用AutoFac依赖注入

这里贴出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、重新生成发布项目,完成

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI