Autofac 动态获取对象静态类获取对象

Autofac 从容器中获取对象

静态类或Service场景可以动态,可以直接动态获取对象

Copy
/// <summary> /// 从容器中获取对象 /// </summary> /// <typeparam name="T"></typeparam> public static T GetFromFac<T>() { return _container.Resolve<T>(); }

使用方法:#

Startup->ConfigureServices-> 加入代码 AutofacCore.InitContainer(container);

2020-06-10_174250.png

AutofacCore类:

Copy
using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace CodeHelper { public static class AutofacCore { private static IContainer _container; public static void InitContainer(IContainer container) { _container = container; } public static IContainer InitAutofac(IServiceCollection services) { var builder = new ContainerBuilder(); //注册数据库基础操作和工作单元 //services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); //services.AddScoped(typeof(IUnitWork), typeof(UnitWork)); //注册app层(废弃->不使用此方法,修改采用配置文件) //builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()); ////防止单元测试时已经注入 //if (services.All(u => u.ServiceType != typeof(ICacheContext))) //{ // services.AddScoped(typeof(ICacheContext), typeof(CacheContext)); //} //if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor))) //{ // services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor)); //} //将配置添加到ConfigurationBuilder //var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()); //config.AddJsonFile("autofac.json"); //config.AddJsonFile来自Microsoft.Extensions.Configuration.Json //config.AddXmlFile来自Microsoft.Extensions.Configuration.Xml //用Autofac注册ConfigurationModule //var module = new ConfigurationModule(config.Build()); //builder.RegisterModule(module); //builder.Populate(services); //_container = builder.Build(); return _container; } /// <summary> /// 从容器中获取对象 /// </summary> /// <typeparam name="T"></typeparam> public static T GetFromFac<T>() { return _container.Resolve<T>(); } } }

代码调用:#

Copy
var Configuration = AutofacCore.GetFromFac<IConfiguration>(); AppId = Configuration["AppSettings:AppId"]; AppSecret = Configuration["AppSettings:AppSecret"];
posted @   Homegu  阅读(1119)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
你的浏览器不支持canvasr
点击右上角即可分享
微信分享提示
CONTENTS