.NET Core3.0 Autofac注入
2024-08-24 20:36:40
参考地址:https://docs.autofac.org/en/latest/examples/index.html
1. nuget :Autofac.Extensions.DependencyInjection Autofac.Extras.DynamicProxy
2.
using System.IO;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting; namespace DL.Admin
{
public class Program
{
public static void Main(string[] args)
{
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:2020")
.UseStartup<Startup>();
});
}
}
}
3. 启动文件Startup.cs内部添加以下方法
public void ConfigureContainer(ContainerBuilder builder)
{
//添加任何Autofac模块或注册。
//这是在ConfigureServices之后调用的,所以
//在此处注册将覆盖在ConfigureServices中注册的内容。
//在构建主机时必须调用“UseServiceProviderFactory(new AutofacServiceProviderFactory())”`否则将不会调用此。 builder.RegisterModule(new AutofacModuleRegister(Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath, new List<string>()
{ //批量构造函数注入
"DL.Service.dll",
})); builder.RegisterType<Log4netService>()
.As<ILogService>()
.PropertiesAutowired()//开始属性注入
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例 builder.RegisterType<JwtService>()
.As<ITokenService>()
.PropertiesAutowired()//开始属性注入
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例 }
3. 创建下面类,进行批量注入
using Autofac;
using Autofac.Extras.DynamicProxy;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Module = Autofac.Module; namespace DL.Utils.Autofac
{
public class AutofacModuleRegister : Module
{
public string RootPath { get; set; }
public List<string> DllFiles { get; set; }
public AutofacModuleRegister(string rootPath, List<string> dllFiles)
{
RootPath = rootPath;
DllFiles = dllFiles;
} protected override void Load(ContainerBuilder builder)
{
foreach (var dllFile in DllFiles)
{
var dllFilePath = Path.Combine(RootPath, dllFile);//获取项目绝对路径
builder.RegisterAssemblyTypes(Assembly.LoadFile(dllFilePath))//直接采用加载文件的方法
//.PropertiesAutowired()//开始属性注入
//.Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()//表示注册的类型,以接口的方式注册不包括IDisposable接口
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy,使用接口的拦截器,在使用特性 [Attribute] 注册时,注册拦截器可注册到接口(Interface)上或其实现类(Implement)上。使用注册到接口上方式,所有的实现类都能应用到拦截器。
.InstancePerLifetimeScope();//即为每一个依赖或调用创建一个单一的共享的实例
} ////拦截器
////builder.Register(c => new AOPTest());
////注入类
////builder.RegisterType<UsersService>().As<UsersIService>().PropertiesAutowired().EnableInterfaceInterceptors(); ////程序集注入
//var IRepository = Assembly.Load("DL.IRepository");
//var Repository = Assembly.Load("DL.Repository");
//Assembly.GetExecutingAssembly();
////根据名称约定(仓储层的接口和实现均以Repository结尾),实现服务接口和服务实现的依赖
//builder.RegisterAssemblyTypes(IRepository, Repository)
// .Where(t => t.Name.EndsWith("Repository"))
// .AsImplementedInterfaces(); }
}
}
4. Startup.cs的ConfigureServices 方法添加
services.AddControllersWithViews()
.AddControllersAsServices();//这里要写
4. Startup.cs的Configure 方法添加进行测试
using (var container = host.Services.CreateScope())
{
//ICacheService phone = container.ServiceProvider.GetService<ICacheService>();
//phone.Set<string>("1", "123");
ILogService log = container.ServiceProvider.GetService<ILogService>();
log.Debug(typeof(string), "mesg", new[] { "1", "2" }); //var str = phone.Get<string>("1"); IService.SysIservice.ISysAdminService sysAdminService = container.ServiceProvider.GetService<IService.SysIservice.ISysAdminService>(); var list = sysAdminService.GetListAsync();
}
最新文章
- 无法建立SSL连接
- JS传中文到后台需要的处理
- Java——线程间通信问题
- VirtualBox是什么
- 一个利用sed和awk处理文本的小栗子
- select2的基本用法
- 1到n数组,和为指定数所有序列问题
- hdu 1196
- python学习日记(内置、匿名函数练习题)
- 使用jconsole分析内存情况-JVM
- 怎么取cxgrid某一列的合计值
- 用level-list让同一个ImageView根据条件来显示不同的内容
- 如何确定HyperThreading是否在Linux上已开启?
- mongodb自动关闭:页面太小,无法完成操作
- SQL Server 查询优化 索引的结构与分类
- vs的 Avalon 自动补全
- 侯捷stl学习笔记链接
- MVC中FileResult 返回类型返回Excel
- 20145209 2016-2017-2 《Java程序设计》第4周学习总结
- [USACO 2018 Feb Gold] Tutorial