作者:enlend_443 | 来源:互联网 | 2023-09-12 16:55
Autofac 从容器中获取对象
静态类或Service场景可以动态,可以直接动态获取对象
///
/// 从容器中获取对象
///
///
public static T GetFromFac()
{
return _container.Resolve();
}
使用方法:
Startup->ConfigureServices-> 加入代码 AutofacCore.InitContainer(container);
AutofacCore类:
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;
}
///
/// 从容器中获取对象
///
///
public static T GetFromFac()
{
return _container.Resolve();
}
}
}
代码调用:
var COnfiguration= AutofacCore.GetFromFac();
AppId = Configuration["AppSettings:AppId"];
AppSecret = Configuration["AppSettings:AppSecret"];
作者:GG
出处:https://www.cnblogs.com/codedisco
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。