ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入

一、准备工作

通过程序包管理器控制台安装AutoFac:

Install-Package Autofac.Extensions.DependencyInjection

创建新类库(.NetCore 2.2类库),存放接口跟实现类,命名为NetCoreWebApi.Repository。

创建用户仓储接口

在类库项目上右键->添加->新建文件夹,命名为Interface,存放接口类。在Interface文件夹下面新建类:IUserRepository,属性如下:

using System.Collections.Generic;
using NetCoreWebApi.Model.Models;

namespace NetCoreWebApi.Repository.Interface
{
    /// 
    /// 用户接口
    /// 
    public interface IUserRepository
    {
        /// 
        /// 添加用户
        /// 
        /// 实体对象
        int Add(TbUser entity);
        /// 
        /// 删除用户
        /// 
        /// 实体对象
        int Remove(TbUser entity);
        /// 
        /// 编辑用户
        /// 
        /// 实体对象
        /// 
        int Update(TbUser entity);
        /// 
        /// 获取所有 
        /// 
        /// 
        IList GetAll();
    }
}

创建用户接口实现类

在类库项目上右键->添加->新建文件夹,命名为Implement,存放接口实现类。在Implement文件夹下面新建类:UserRepository,属性如下:

using System.Collections.Generic;
using System.Linq;
using NetCoreWebApi.Model;
using NetCoreWebApi.Model.Models;
using NetCoreWebApi.Repository.Interface;

namespace NetCoreWebApi.Repository.Implement
{
    /// 
    /// 业务处理
    /// 
    public class UserRepository:IUserRepository
    {
        private readonly MyDbContext _dbContext;
        /// 
        /// 构造函数
        /// 
        /// 
        public UserRepository(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        /// 
        /// 添加用户
        /// 
        /// 
        /// 
        public int Add(TbUser entity)
        {
            _dbContext.TbUsers.Add(entity);
            return _dbContext.SaveChanges();
        }
        /// 
        /// 删除用户
        /// 
        /// 
        /// 
        public int Remove(TbUser entity)
        {
            _dbContext.TbUsers.Remove(entity);
            return _dbContext.SaveChanges();
        }
        /// 
        /// 编辑用户
        /// 
        /// 
        /// 
        public int Update(TbUser entity)
        {
            return _dbContext.SaveChanges();
        }
        /// 
        /// 查询用户
        /// 
        /// 
        public IList GetAll()
        {
            return _dbContext.TbUsers.ToList();
        }
    }
}

二、配置注入

打开Startup.cs类

把ConfigureServices方法的返回值由void变为IServiceProvider

        public static IContainer ApplicationContainer { get; set; }
        /// 
        /// //负责注入服务
        /// 
        /// 
        /// 
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var connectionStr = Configuration.GetConnectionString("SqlServer");
            services.AddDbContext
                (options => options.UseSqlServer(connectionStr,
                    e => e.MigrationsAssembly("NetCoreWebApi.Model")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //初始化容器
            var builder = new ContainerBuilder();
            //管道寄居
            builder.Populate(services);
            //注册仓储,IUserRepository接口到UserRepository的映射
            builder.RegisterType().As();
            //构造
            ApplicationContainer = builder.Build();
            //将AutoFac反馈到管道中
            return new AutofacServiceProvider(ApplicationContainer);
        }

三、测试

在项目上右键->添加->新建文件夹,命名为Controllers,存放相应的控制器。在Controllers文件夹下面新建一个控制器:UserController,如下:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using NetCoreWebApi.Model.Models;
using NetCoreWebApi.Repository.Interface;

namespace NetCoreWebApi.Controllers
{
    /// 
    /// 用户模块
    /// 
    [Route("api/user")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository _userRepository;

        /// 
        /// 构造函数
        /// 
        /// 
        public UserController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        /// 
        /// 创建用户
        /// 
        /// 
        [Route("createUser")]
        [HttpPost]
        public TbUser CreateUser()
        {
            var user = new TbUser
            {
                UserId = Guid.NewGuid().ToString("N"),
                CreateTime = DateTime.Now,
                UserName = "tenghao",
                Email = "[email protected]"
            };
            _userRepository.Add(user);
            return user;
        }
        /// 
        /// 查询用户
        /// 
        /// 
        [Route("getUser")]
        [HttpGet]
        public IList GetUser()
        {
            return _userRepository.GetAll();
        }
    }
}

Ctrl+F5 运行之后,先用Postman调创建用户接口

ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入_第1张图片

 

接下来测试下查询用户

ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入_第2张图片

好了,你们自己测下写的有没有问题。

你可能感兴趣的:(ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入)