ASP.NET Core中使用Autofac进行属性注入
一些无关紧要的废话:
作为一名双修程序员(自封的),喜欢那种使用Spring的注解形式进行依赖注入或者Unity的特性形式进行依赖注入,当然,形式大同小异,但结果都是一样的,通过属性进行依赖注入。
ASP.NET Core中使用了自带的Dependency Injection作为了默认的IOC容器,当然有先天的优势,很多还是喜欢切换到Autofac作为IOC容器,Unity在.Net Core中还是有很大的优势的,但据我所知,Unity5已经由微软转交到基金会了,而且本身文档很少,翻译文档以及研究的就更加少了。
当然,说了一堆废话,Autofac本身也是支持属性注入的,但是很多还是使用构造器进行注入,我本身也是推荐使用构造器进行注入(其实我不是这么想的),因为使用属性进行注入,将会暴露当前类的属性(Autofac属性注入属性必须为public),Spring可以用private进行注入的,但是不知道为什么,Autofac我使用private的时候注入进来的时候是null,如果文章有错误的话,希望高手能在留言处指出,帮助我及更多人进步。谢谢。
⒈新建一个ASP.NET Core MVC程序。
⒉添加 NuGet 包
Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection
⒊新建实体类,服务抽象,服务实现。(DAL我这里就省略了,自行脑部)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace DapperDemo.Models
{
public class User
{
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public int enabled { get; set; }
}
}
using DapperDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace DapperDemo.Services
{
public interface IUserService
{
IList<User> GetUsers();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DapperDemo.Models; namespace DapperDemo.Services.Impl
{
public class UserService : IUserService
{
public IList<User> GetUsers()
{
return new List<User>
{
new User
{
id = ,
username = "fanqi",
password = "admin",
enabled =
}
};
}
}
}
⒋新建一个Aufofac Module,配置注入
using Autofac;
using DapperDemo.Services;
using DapperDemo.Services.Impl;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks; namespace DapperDemo.Module
{
public class DefaultModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{ builder.RegisterType<UserService>().As<IUserService>().PropertiesAutowired()
.InstancePerLifetimeScope(); var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(); }
}
}
⒌修改Startup,替换IOC,使用Autofac作为默认的IOC容器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using DapperDemo.Module;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; namespace DapperDemo
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices(); // 添加 Autofac
var containerBuilder = new ContainerBuilder(); containerBuilder.Populate(services); containerBuilder.RegisterModule<DefaultModule>(); var container = containerBuilder.Build(); return new AutofacServiceProvider(container);
} // 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?}");
});
}
}
}
⒍新建控制器,在属性中注入服务抽象实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DapperDemo.Models;
using DapperDemo.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; namespace DapperDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
public IUserService UserService { protected get; set; } [Route("get")]
public IList<User> GetUsers()
{
return UserService.GetUsers();
} }
}
⒎测试

ASP.NET Core中使用Autofac进行属性注入的更多相关文章
- Asp.Net Core 中利用QuartzHostedService 实现 Quartz 注入依赖 (DI)
QuartzHostedService 是一个用来在Asp.Net Core 中实现 Quartz 的任务注入依赖的nuget 包: 基本示例如下: using System; using Syst ...
- ASP.NET Core Web 应用程序系列(三)- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)
在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入,本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入. 约定: 1.仓储层接口 ...
- ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)
在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...
- 在ASP.Net Core下,Autofac实现自动注入
之前使用以来注入的时候,都是在xml配置对应的接口和实现类,经常会出现忘了写配置,导致注入不生效,会报错,而且项目中使用的是SPA的模式,ajax报错也不容易看出问题,经常会去排查日志找问题. 于是在 ...
- ASP.NET Core 中的框架级依赖注入
https://tech.io/playgrounds/5040/framework-level-dependency-injection-with-asp-net-core 作者: Gunnar P ...
- ASP.NET Core中使用Autofac
⒈添加相关依赖 Install-Package Autofac ⒉扫描项目接口实现类 using Autofac; using System; using System.Collections.Gen ...
- ASP.NET Core中使用自定义验证属性控制访问权限
在应用中,有时我们需要对访问的客户端进行有效性验证,只有提供有效凭证(AccessToken)的终端应用能访问我们的受控站点(如WebAPI站点),此时我们可以通过验证属性的方法来解决. 一.publ ...
- ASP.NET Core中使用自定义MVC过滤器属性的依赖注入
除了将自己的中间件添加到ASP.NET MVC Core应用程序管道之外,您还可以使用自定义MVC过滤器属性来控制响应,并有选择地将它们应用于整个控制器或控制器操作. ASP.NET Core中常用的 ...
- 如何解决 ASP.NET Core 中的依赖问题
依赖性注入是一种技术,它允许我们注入一个特定类的依赖对象,而不是直接创建这些实例. 使用依赖注入的好处显而易见,它通过放松模块间的耦合,来增强系统的可维护性和可测试性. 依赖注入允许我们修改具体实现, ...
随机推荐
- flask框架(四):通过局域网访问网站
一:开启局域网访问 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) # 设置成局域网访问 二:设置windows的入站规则 ...
- vue项目中主要文件的加载顺序(index.html、main.js、App.vue)
todo: https://www.cnblogs.com/xifengxiaoma/p/9493544.html https://www.cnblogs.com/stella1024/p/10563 ...
- Teamviewer解决许可证授权的问题
提交商业用途表 https://www.teamviewer.com/zhCN/pricing/commercial-use/
- y7000笔记本 darknet-yolo安装与测试(Ubuntu16.04+Cuda9.0+Cudnn7.1)
https://zhuanlan.zhihu.com/p/41096599 1.先查看是否安装有以下组件,若有先考虑彻底删除再安装(安装严格按照下面顺序进行) 查看nvidia 版本 nvidia-s ...
- JDK7 JDK8 的安装 且不同版本之间的切换
myeclipse 论坛下载 https://www.myeclipsecn.com/download/ 用户名:xcj26 邮箱:xcj26@126.com 密码: 26**_X** 版本: Jav ...
- CSS标签详解
CSS3标签 Css3概述 从2010年开始,HTML5与CSS3就一直是互联网技术中最受关注的两个话题.从前端技术的角度可以把互联网的发展分为三个阶段:第一阶段是web1.0以内容为主的网络,前端主 ...
- SRS之HLS部署实例源码分析
1. 综述 SRS 关于 HLS 的具体配置可见: HLS部署实例 SRS 关于 hls 的配置文件内容如下: listen 1935; max_connections 1000; daemon of ...
- python 异常和弹出框
import tkinter.messagebox try: fileContent = open("abnormal.txt") fileContent.close() prin ...
- 黑马vue---10-11、Vue实现跑马灯效果
黑马vue---10-11.Vue实现跑马灯效果 一.总结 一句话总结: 1. 给 [浪起来] 按钮,绑定一个点击事件 v-on @ 2. 在按钮的事件处理函数中,写相关的业务逻辑代码:拿到 ...
- LC 656. Coin Path 【lock, Hard】
Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The ...