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 中的依赖问题
依赖性注入是一种技术,它允许我们注入一个特定类的依赖对象,而不是直接创建这些实例. 使用依赖注入的好处显而易见,它通过放松模块间的耦合,来增强系统的可维护性和可测试性. 依赖注入允许我们修改具体实现, ...
随机推荐
- Trie树(c++实现)——转载自jihite的博客
Trie树(c++实现) 原理 先看个例子,存储字符串abc.ab.abm.abcde.pm可以利用以下方式存储 上边就是Trie树的基本原理:利用字串的公共前缀来节省存储空间,最大限度的减少无谓 ...
- 创建虚拟机,安装操作系统,xshell6远程链接
一.创建虚拟机 1. 首先安装vmware,注意在安装中,下面的两项不要勾选,一路下一步 2.完成安装打开之后,创建新的虚拟机 3.虚拟机创建完成,需要改配置 4.然后设置网段 5.查看服务,在运行状 ...
- Oracle实现分页,每页有多少条记录数
分页一直都是关系数据库的热门,在数据量非常多的情况下,需要根据分页展示,每页展示多少条记录,以此减轻数据的压力; 1实现原理,根据rownum取记录数,根据公式(页数-1)*每页想要展示的记录数 AN ...
- 微信小程序_(校园视)开发上传视频业务
微信小程序_(校园视) 开发用户注册登陆 传送门 微信小程序_(校园视) 开发上传视频业务 传送门 微信小程序_(校园视) 开发视频的展示页-上 传送门 微信小程序_(校园视) 开发视频的展示页-下 ...
- LNMP源码编译
LNMP源码编译 编译安装之前把开发包组安装了 [root@tiandong63 ~]# yum groupinstall "Development Tools" "De ...
- 初识 Premiere
本记录基于Premiere Pro CC 2015.3,编号不连贯,以视频编号为准,对应视频没有有用信息的没有记录. 1.3 基本工作界面和预设工作区 将面板独立出来:按住Ctrl拖动窗口 将关闭的面 ...
- dnSpy PE format ( Portable Executable File Format)
Portable Executable File Format PE Format 微软官方的 What is a .PE file in the .NET framework? [closed] ...
- 六、Jmeter中自动提取Http请求参数,并put到Map,然后进行MD5加密
1.BeanShell PerOrocessor中的脚本 import src.com.csjin.qa.MD5.*;//个人jar包 import java.util.*; import java. ...
- ServiceStatusUtils判断服务是否运行
import android.app.ActivityManager; import android.app.Service; import android.content.Context; impo ...
- 如何在网页中添加 jQuery。
转自:http://www.runoob.com/jquery/jquery-install.html 网页中添加 jQuery 可以通过多种方法在网页中添加 jQuery. 您可以使用以下方法: 从 ...