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 中的依赖问题
依赖性注入是一种技术,它允许我们注入一个特定类的依赖对象,而不是直接创建这些实例. 使用依赖注入的好处显而易见,它通过放松模块间的耦合,来增强系统的可维护性和可测试性. 依赖注入允许我们修改具体实现, ...
随机推荐
- [sdoi 2010][bzoj 1925]地精部落(神仙dp)
Description 传说很久以前,大地上居住着一种神秘的生物:地精. 地精喜欢住在连绵不绝的山脉中.具体地说,一座长度为 N 的山脉 H可分 为从左到右的 N 段,每段有一个独一无二的高度 Hi, ...
- 两个线程,一个线程打印1~52,另一个线程打印字母A-Z,打印顺序为12A34B56C……5152Z
使用wait,notify实现 public class Test { public synchronized void a() { for (int i = 1; i <= 52; i++) ...
- Suitable Replacement
D. Suitable Replacement 这个题统计出 s 和 t 中的各字母个数以及"?"的个数,直接暴力即可,s中不足的字母可用 "?"来替代 这个题 ...
- Python实现telnet命令测试防火墙
Python实现telnet命令测试防火墙 telnet主要用于测试主机端口是否开通 ping主要是用来测试网络是否畅通和主机是否正在使用 使用Python实现Telnet测试主机端口是否开通的功能. ...
- Flume使用
avro agent 配置文件 cd $FLUME_HOME/conf vim avro.conf a1.sources = r1 a1.sinks = k1 a1.channels = c1 a1. ...
- ettercap局域网DNS切换到恶意网址
ettercap -i eth0 -Tq -M arp:remote -P dns_spoof /// /// Dns欺骗--Ettercap工具进行Dns欺骗 转载至 https://blog.cs ...
- 【实用软件】GIF屏幕录制软件-ScreenToGif (在GitHub开源)
抛个问题,自问自答 ScreenToGif 经常会遇到一些场景,需要你向别人展示一些操作或是效果——例如告诉别人某某软件的配置步骤啊.刚某个动画效果怎么样啊.某某电影里面的一个镜头多么经典啊.打得大快 ...
- linux 禁ping
今天用nmap扫描了局域网的主机,发现几个主机开着好多危险端口,做linux的,对这些安全知识有一点了解.遂用nmap扫描了自己的主机是否存在可利用端口.发现每次nmap都能成功的检测我的主机是ali ...
- Struts2类数据封装
- Eclipse 设置护眼背景色
Eclipse 设置护眼背景色 1.设置字体大小 Window --> Preferences --> General --> Apprearance --> Colors a ...