ASP.NET Core中使用Autofac进行属性注入
2024-10-21 09:45:20
一些无关紧要的废话:
作为一名双修程序员(自封的),喜欢那种使用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();
} }
}
⒎测试
最新文章
- Python之路 day2 初识字典
- MySQl的几个配置项
- display和visibility的区别
- Nginx负载趟过的坑
- spark(一) build
- http://www.cutt.com/
- linux kernel 结构体赋值方法{转载}
- opencv编程入门技巧
- 微信小程序开发之获取openid及用户信息
- bootstrap-table前台和后台分页对json格式的要求
- Redis和nosql简介,api调用;Redis数据功能(String类型的数据处理);List数据结构(及Java调用处理);Hash数据结构;Set数据结构功能;sortedSet(有序集合)数
- 数组中的数分为两组,让给出一个算法,使得两个组的和的差的绝对值最小,数组中的数的取值范围是0<;x<;100,元素个数也是大于0, 小于100 。
- object类和内部类
- Jmeter读取Excel,BeanShell取样器调用rt.jar和jxl.jar
- linux(fedora) 第三课
- 跟我一起用node-express搭建一个小项目(node连接mongodb)[三]
- php : 文件及文件夹操作(创建、删除、移动、复制)
- linux系统中查看己设置iptables规则
- WinForm 随手记
- (诊断)解决GitHub使用双因子身份认证“Two-Factor Athentication”后无法git push 代码的“fatal: Authentication failed for ...”错误
热门文章
- c++顺序表(数组)查找最大最小值
- 11.EL(表达式语言)
- JavaWeb-SpringBoot(抖音)_三、抖音项目后续
- vue-cli脚手架构建了项目,想去除Eslint验证,如何设置?
- Error:java: 错误: 不支持发行版本 5
- 浅析history hack、心血漏洞、CSS欺骗、SQL注入与CSRF攻击
- ORA-00600: internal error code, arguments: [kdBlkCheckError]
- 热门搜索词获取java版
- SAS数据挖掘实战篇【三】
- Window Relationships and Frames