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 中的依赖问题
依赖性注入是一种技术,它允许我们注入一个特定类的依赖对象,而不是直接创建这些实例. 使用依赖注入的好处显而易见,它通过放松模块间的耦合,来增强系统的可维护性和可测试性. 依赖注入允许我们修改具体实现, ...
随机推荐
- 微信小程序_(表单组件)button组件的使用
微信小程序表单组件button官方文档 传送门 Learn 一.button组件的使用 一.button组件的使用 size:按钮的大小[默认值default] type:按钮的样式类型[默认值def ...
- MySQL_(Java)提取工具类JDBCUtils
MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC创建用户名和密码校验查询方法 传送门 MySQL_(Java)使用preparestatement ...
- 使用yum安装nginx
在CentOS 7中安装Nginx. 当使用以下命令安装Nginx时,发现无法安装成功. 1 yum install -y nginx 需要做一点处理. 安装Nginx源 执行以下命令: 1 rpm ...
- python3精品解析运算符
算数运算符 +:两个对象相加 -:得到负数或者,或者一个数减去另一个数 *:两个数相乘或者是返回一个被重复若干次的字符串 /:5/2等于2.1 5//2=2(/有余数,//取整) %:取模(5%2=1 ...
- 关于一次同余方程的一类解法(exgcd,CRT,exCRT)
1.解同余方程: 同余方程可以转化为不定方程,其实就是,这样的问题一般用拓展欧几里德算法求解. LL exgcd(LL a,LL b,LL &x,LL &y){ if(!b){ x=; ...
- SSH中一些典型的问题
struts2 1-1:为什么每次请求都要创建一个Action对象? 是出于对线程安全的考虑,每个request都不会相互影响 1-2:ModelDriven拦截器的配置中refreshModelBe ...
- Java内存缓存-通过Google Guava创建缓存
谷歌Guava缓存 Guava介绍 Guava是Google guava中的一个内存缓存模块,用于将数据缓存到JVM内存中.实际项目开发中经常将一些公共或者常用的数据缓存起来方便快速访问. Guava ...
- Springboot websocket使用
1)基本概念 1.http与websocket http超文本传输协议,大家都非常熟悉,http有1.0.1.1. 2.0几个版本,从http1.1起,默认都开启了Keep-Alive,保持连接持续性 ...
- 测试linux服务器是否能接入微信
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319 php.代码 <?php $a = $_GE ...
- websphere启动报:Could not resolve placeholder 'hibernate.hbm2ddl.auto' in string value "${hibernate.hbm2ddl.auto}"
websphere启动报/WEB-INF/applicationContext-orm- hibernate.xml]: Could not resolve placeholder 'hibernat ...