ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)...

在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入。

PS:本章将主要采用构造函数注入的方式,下一章将继续分享如何使之能够同时支持属性注入的方式。

约定:

1、仓储层接口都以“I”开头,以“Repository”结尾。仓储层实现都以“Repository”结尾。

2、服务层接口都以“I”开头,以“Service”结尾。服务层实现都以“Service”结尾。

接下来我们正式进入主题,在上一章的基础上我们再添加一个web项目TianYa.DotNetShare.CoreAutofacMvcDemo,首先来看一下我们的解决方案

本demo的web项目为ASP.NET Core Web 应用程序(.NET Core 2.2) MVC框架,需要引用以下几个程序集:

1、TianYa.DotNetShare.Model 我们的实体层

2、TianYa.DotNetShare.Service 我们的服务层

3、TianYa.DotNetShare.Repository 我们的仓储层,正常我们的web项目是不应该使用仓储层的,此处我们引用是为了演示IOC依赖注入

4、Autofac 依赖注入基础组件

5、Autofac.Extensions.DependencyInjection 依赖注入.NET Core的辅助组件

其中Autofac和Autofac.Extensions.DependencyInjection需要从我们的NuGet上引用,依次点击下载以下2个包:

接着我们在web项目中添加一个类AutofacModuleRegister.cs用来注册Autofac模块,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;using Autofac;namespace TianYa.DotNetShare.CoreAutofacMvcDemo
{/// <summary>/// 注册Autofac模块/// </summary>public class AutofacModuleRegister : Autofac.Module{/// <summary>/// 重写Autofac管道Load方法,在这里注册注入/// </summary>protected override void Load(ContainerBuilder builder){builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();//注册MVC控制器(注册所有到控制器,控制器注入,就是需要在控制器的构造函数中接收对象)builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.CoreAutofacMvcDemo")).Where(a => a.Name.EndsWith("Controller")).AsImplementedInterfaces();}/// <summary>/// 根据程序集名称获取程序集/// </summary>/// <param name="assemblyName">程序集名称</param>public static Assembly GetAssemblyByName(string assemblyName){return Assembly.Load(assemblyName);}}
}

然后打开我们的Startup.cs文件进行注入工作,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;using Autofac;
using Autofac.Extensions.DependencyInjection;namespace TianYa.DotNetShare.CoreAutofacMvcDemo
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public IServiceProvider ConfigureServices(IServiceCollection services){services.Configure<CookiePolicyOptions>(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_2);return RegisterAutofac(services); //注册Autofac
        }// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseCookiePolicy();app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});}/// <summary>/// 注册Autofac/// </summary>private IServiceProvider RegisterAutofac(IServiceCollection services){//实例化Autofac容器var builder = new ContainerBuilder();//将services中的服务填充到Autofac中
            builder.Populate(services);//新模块组件注册    builder.RegisterModule<AutofacModuleRegister>();//创建容器var container = builder.Build();//第三方IoC容器接管Core内置DI容器 return new AutofacServiceProvider(container);}}
}

PS:需要将自带的ConfigureServices方法的返回值改成IServiceProvider

接下来我们来看看控制器里面怎么弄:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TianYa.DotNetShare.CoreAutofacMvcDemo.Models;using TianYa.DotNetShare.Service;
using TianYa.DotNetShare.Repository;namespace TianYa.DotNetShare.CoreAutofacMvcDemo.Controllers
{public class HomeController : Controller{/// <summary>/// 定义仓储层学生抽象类对象/// </summary>protected IStudentRepository StuRepository;/// <summary>/// 定义服务层学生抽象类对象/// </summary>protected IStudentService StuService;/// <summary>/// 通过构造函数进行注入/// 注意:参数是抽象类,而非实现类,因为已经在Startup.cs中将实现类映射给了抽象类/// </summary>/// <param name="stuRepository">仓储层学生抽象类对象</param>/// <param name="stuService">服务层学生抽象类对象</param>public HomeController(IStudentRepository stuRepository, IStudentService stuService){this.StuRepository = stuRepository;this.StuService = stuService;}public IActionResult Index(){var stu1 = StuRepository.GetStuInfo("10000");var stu2 = StuService.GetStuInfo("10001");string msg = $"学号:10000,姓名:{stu1.Name},性别:{stu1.Sex},年龄:{stu1.Age}<br />";msg += $"学号:10001,姓名:{stu2.Name},性别:{stu2.Sex},年龄:{stu2.Age}";return Content(msg, "text/html", System.Text.Encoding.UTF8);}public IActionResult Privacy(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}}
}

至此完成处理,接下来就是见证奇迹的时刻了,我们来访问一下/home/index,看看是否能返回学生信息。

可以发现,返回了学生的信息,说明我们注入成功了。

至此,本章就介绍完了,如果你觉得这篇文章对你有所帮助请记得点赞哦,谢谢!!!

demo源码:

链接:https://pan.baidu.com/s/1un6_wgm6w_bMivPPRGzSqw 
提取码:lt80

 

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

转载于:https://www.cnblogs.com/xyh9039/p/11379831.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/247110.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

iOS手势操作简介(五)

利用手势操作实现抽屉效果&#xff1a; 第一步&#xff1a;搭建UI (void)addChildView { // left UIView *leftView [[UIView alloc] initWithFrame:self.view.bounds]; leftView.backgroundColor [UIColor greenColor]; [self.view addSubview:leftView]; _leftView…

Java过滤器与SpringMVC拦截器之间的关系与区别

今天学习和认识了一下&#xff0c;过滤器和SpringMVC的拦截器的区别&#xff0c;学到了不少的东西&#xff0c;以前一直以为拦截器就是过滤器实现的&#xff0c;现在想想还真是一种错误啊&#xff0c;而且看的比较粗浅&#xff0c;没有一个全局而又细致的认识&#xff0c;由于已…

iOS手势操作简介(六)

利用UIGestureRecognizer来对手势进行处理&#xff1a; interface HMViewController () property (weak, nonatomic) IBOutlet UIImageView *imagView; end implementation HMViewController (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup aft…

iOS并行程序开发- GCD NSOperationQueue(1)

import UIKit let imageURLs [“http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg“, “http://adriatic-lines.com/wp-content/uploads/2015/04/canal-of-Venice.jpg“, “http://algoos.com/wp-content/uploads/2015/08/ireland-02.jpg“, “http:…

二次幂权限设计

设置含有的权限如增删改查减为1,2,4,8,16 如果A包含增删改这5个权限&#xff0c;那A的值为1247 如果B包含增改查这5个权限&#xff0c;那A的值为14813 如果C包含增删改查减这5个权限&#xff0c;那A的值为12481631 7二进制为111,13的二进制为1101,31二进制为11111 1二进制为1&a…

最好用的koa2+mysql的RESTful API脚手架,mvc架构,支持node调试,pm2部署。

#基于webpack构建的 Koa2 restful API 服务器脚手架这是一个基于 Koa2 的轻量级 RESTful API Server 脚手架&#xff0c;支持 ES6, 支持使用TypeScript编写。GIT地址&#xff1a;https://github.com/Allenzihan/koa2-mysql-framework.git此脚手架只安装了一些配合koa2使用的必要…

使用putty在linux主机和windows主机之间拷贝文件(已测试可执行)

转载于&#xff0c;请点击 首先下载putty&#xff0c;putty下载地址zip&#xff0c; 解压zip发现里面有plink.exe pscp.exe psftp.exe putty.exe puttygen.exe puttytel.exe等可执行文件&#xff0c;如果只是想要链接主机做一些操作那么使用putty.exe&#xff0c;要想要上传 …

博客园在升级的路上,不妨更自信些,同时说说我们可以为博客园做些什么

最近&#xff0c;博客园在技术升级上做了积极向上的努力&#xff0c;虽然中间过程出现反复&#xff0c;但姑且先不论最终升级后客户体验方面的提升&#xff0c;在升级过程中探索排查问题和解决问题的过程&#xff0c;本身就能帮助博客园团队和广大用户积累经验和提升能力&#…

iOS中持久化存储SQLite(一)

在iOS中做持久化存储有多种方案&#xff0c;其中包括plist, preference, sqlite, core data,其中&#xff1a; &#xff08;1&#xff09;plist, preference适合小型数据存储&#xff0c;因为每次存储前都必须将文件内容读到内存中&#xff0c;因此如果数据量过大就会占用大量…

多进程相关内容

多进程相关内容 multiprocessing模块与process类 multiprocessing python中的多线程无法利用多核优势&#xff0c;如果想要充分地使用多核CPU的资源&#xff08;os.cpu_count()查看&#xff09;&#xff0c;在python中大部分情况需要使用多进程。Python提供了multiprocessing。…

iOS中SQLite持久化存储第三方库FMDB

interface HMShopTool : NSObject (NSArray *)shops; (void)addShop:(HMShop *)shop; end implementation HMShopTool static FMDatabase *_db; (void)initialize { // 1.打开数据库 NSString *path [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, N…

python超神之路:python异常对照表

python异常对照表 异常名称描述BaseException所有异常的基类SystemExit解释器请求退出KeyboardInterrupt用户中断执行(通常是输入^C)Exception常规错误的基类StopIteration迭代器没有更多的值GeneratorExit生成器(generator)发生异常来通知退出StandardError所有的内建标准异常…

python超神之路:创建对象的9种方法

python生成对象的9种方法 class Point:def __init__(self,x,y):self.x xself.y y import sys import copy import typespoint1 Point(1,2) point2 eval("{}({},{})".format("Point",1,2)) point3 globals()[Point](1,2) point4 locals()["Point…

面向接口的编程

面向接口的编程&#xff0c;将接口与实现分离&#xff0c;可以极大的降低代码的耦合&#xff0c;比如在编程中使用的加密接口&#xff0c;如果将具体的加密算法写入到使用加密的地方&#xff0c;这样就会导致&#xff0c;下一次加密方法发生改变的时候会导致大量的地方需要修改…

ASP.NET Core Web 应用程序系列(三)- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)...

在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入&#xff0c;本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入。 约定&#xff1a; 1、仓储层接口都以“I”开头&#xff0c;以“Repository”结尾。仓储层实现都以…

可视化caffe模型结构及在线可视化

在线可视化caffe模型结构 http://ethereon.github.io/netscope/#/editor 假设Caffe的目录是$(CAFFE_ROOT) 1.编译caffe的python接口 $ make pycaffe 2.装各种依赖 $ pip install pydot $ sudo apt-get install graphviz 3.可视化模型 draw_net.py执行的时候带三个参数 …

布式缓存系统Memcached简介与实践

缘起: 在数据驱动的web开发中&#xff0c;经常要重复从数据库中取出相同的数据&#xff0c;这种重复极大的增加了数据库负载。缓存是解决这个问题的好办法。但是ASP.NET中的虽然已经可以实现对页面局部进行缓存&#xff0c;但还是不够灵活。此时Memcached或许是你想要的。Memca…

仿百度翻页(转)

https://www.cnblogs.com/fozero/p/9874334.html 转载于:https://www.cnblogs.com/hj0711/p/11390203.html

matlab 多核并行编程

在使用matlab处理大数据&#xff0c;编程需要注意两个问题&#xff1a;并行运算和释放内存。matlab也提供了并行计算的功能&#xff0c;甚至能用GPU加速。并行计算工具箱&#xff0c;叫做parallel computing toolbox.它的使用方法&#xff0c;可以从matlab的帮助获得。 Parall…

iOS核心动画之CALayer(1)

本文目录 一、什么是CALayer二、CALayer的简单使用 回到顶部一、什么是CALayer * 在iOS系统中&#xff0c;你能看得见摸得着的东西基本上都是UIView&#xff0c;比如一个按钮、一个文本标签、一个文本输入框、一个图标等等&#xff0c;这些都是UIView。 * 其实UIView之所以能显…