Asp.Net Core WebApi Swagger+Autofac+JWT的实现(二)

本章将讲下Autofac的注入实现,关于Autofac的讲解以及API参见https://autofaccn.readthedocs.io/zh/latest/getting-started/index.html

项目的基础搭建参见上篇文章https://blog.csdn.net/liwan09/article/details/100733455

Autofac注入的实现

NetCore.App项目从Nuget中添加对Autofac、以及Autofac.Extensions.DependencyInjection两个包的引用

NetCore.WebApi 项目从Nuget中添加Autofac.Extensions.DependencyInjection包的引用

NetCore.App项目中添加AutoFacApp类

using System;
using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using NetCore.Repository;

namespace NetCore.App
{
    /// 
    /// AutoFac 注入
    /// 
    public static class AutoFacApp
    {
        private static IContainer container;
        /// 
        /// 注册组件
        /// 
        /// 
        /// 
        public static IContainer InitAutoFac(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            //注册数据库操作类
            services.AddScoped(typeof(BaseRepository<>));
            services.AddScoped(typeof(UnitWork));
            //注册数据操作类(App层)
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
            builder.Populate(services);
            container = builder.Build();
            return container;
        }
        /// 
        /// 从容器中获取对象
        /// 
        /// 
        public static T GetFromFac()
        {
            return container.Resolve();
        }
    }
}

NetCore.WebApi 项目中的Startup.cs文件修改

 1)将ConfigureServices方法的返回类型修改为IServiceProvider

 2)ConfigureServices方法 中的最后一行代码,返回IServiceProvider

 public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("NetCoreDBContext")));//获取数据库连接 
            return new AutofacServiceProvider(AutoFacApp.InitAutoFac(services));
        }

NetCore.WebApi项目添加对NetCore.App以及NetCore.Repository两个项目的引用,然后在项目中添加UserInfoController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCore.App;
using NetCore.Repository;
using NetCore.Repository.Domain;
using NetCore.Repository.RequestEntity;

namespace NetCore.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserInfoController : ControllerBase
    {
        private readonly UserInfoApp userInfoApp;
        /// 
        /// 构造函数
        /// 
        /// 
        public UserInfoController(UserInfoApp _userInfoApp)
        {
            userInfoApp = _userInfoApp;
        }
        
        /// 
        /// 添加用户信息
        /// 
        /// 用户信息
        /// 
        [HttpPut]
        public ResponseResult Add(UserInfo userInfo)
        {
            if (userInfoApp.IsExist(userInfo.LoginAccount, userInfo.ID))
            {
                return new ResponseResult() { Code = 201, Message = "账户已存在" };
            }
            return userInfoApp.Add(userInfo) ? new ResponseResult() : new ResponseResult() {Code=201,Message="操作失败"};
        }
        /// 
        /// 获取用户信息列表
        /// 
        /// 
        /// 
        [HttpGet]
        public ResponseResult GetUserList(UserInfoRequest userInfoRequest)
        {
            var userList = userInfoApp.GetList(userInfoRequest);
            return new ResponseResult() { DataResult=userList};
        }
    }
}

 可通过PostMan 调用该接口,测试一下,如果取得数据,那么Autofac注入已实现

完整代码下载地址:https://download.csdn.net/download/liwan09/11717224

你可能感兴趣的:(.Net,Core,webApi,C#)