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
{
    /// <summary>
    /// 用戶接口
    /// </summary>
    public interface IUserRepository
    {
        /// <summary>
        /// 添加用戶
        /// </summary>
        /// <param name="entity">實體對象</param>
        int Add(TbUser entity);
        /// <summary>
        /// 刪除用戶
        /// </summary>
        /// <param name="entity">實體對象</param>
        int Remove(TbUser entity);
        /// <summary>
        /// 編輯用戶
        /// </summary>
        /// <param name="entity">實體對象</param>
        /// <returns></returns>
        int Update(TbUser entity);
        /// <summary>
        /// 獲取所有 
        /// </summary>
        /// <returns></returns>
        IList<TbUser> 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
{
    /// <summary>
    /// 業務處理
    /// </summary>
    public class UserRepository:IUserRepository
    {
        private readonly MyDbContext _dbContext;
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="dbContext"></param>
        public UserRepository(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 添加用戶
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Add(TbUser entity)
        {
            _dbContext.TbUsers.Add(entity);
            return _dbContext.SaveChanges();
        }
        /// <summary>
        /// 刪除用戶
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Remove(TbUser entity)
        {
            _dbContext.TbUsers.Remove(entity);
            return _dbContext.SaveChanges();
        }
        /// <summary>
        /// 編輯用戶
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(TbUser entity)
        {
            return _dbContext.SaveChanges();
        }
        /// <summary>
        /// 查詢用戶
        /// </summary>
        /// <returns></returns>
        public IList<TbUser> GetAll()
        {
            return _dbContext.TbUsers.ToList();
        }
    }
}

二、配置注入

打開Startup.cs類

把ConfigureServices方法的返回值由void變為IServiceProvider

        public static IContainer ApplicationContainer { get; set; }
        /// <summary>
        /// //負責注入服務
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var connectionStr = Configuration.GetConnectionString("SqlServer");
            services.AddDbContext<MyDbContext>
                (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<UserRepository>().As<IUserRepository>();
            //構造
            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
{
    /// <summary>
    /// 用戶模塊
    /// </summary>
    [Route("api/user")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository _userRepository;

        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="userRepository"></param>
        public UserController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        /// <summary>
        /// 創建用戶
        /// </summary>
        /// <returns></returns>
        [Route("createUser")]
        [HttpPost]
        public TbUser CreateUser()
        {
            var user = new TbUser
            {
                UserId = Guid.NewGuid().ToString("N"),
                CreateTime = DateTime.Now,
                UserName = "tenghao",
                Email = "tenghao510@qq.com"
            };
            _userRepository.Add(user);
            return user;
        }
        /// <summary>
        /// 查詢用戶
        /// </summary>
        /// <returns></returns>
        [Route("getUser")]
        [HttpGet]
        public IList<TbUser> GetUser()
        {
            return _userRepository.GetAll();
        }
    }
}

Ctrl+F5 運行之后,先用Postman調創建用戶接口

 

接下來測試下查詢用戶

好了,你們自己測下寫的有沒有問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM