Autofac 动态获取对象静态类获取对象
Autofac 从容器中获取对象
静态类或Service场景可以动态,可以直接动态获取对象
/// <summary>
/// 从容器中获取对象
/// </summary>
/// <typeparam name="T"></typeparam>
public static T GetFromFac<T>()
{
return _container.Resolve<T>();
}
使用方法:
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;
}
/// <summary>
/// 从容器中获取对象
/// </summary>
/// <typeparam name="T"></typeparam>
public static T GetFromFac<T>()
{
return _container.Resolve<T>();
}
}
}
代码调用:
var Configuration = AutofacCore.GetFromFac<IConfiguration>();
AppId = Configuration["AppSettings:AppId"];
AppSecret = Configuration["AppSettings:AppSecret"];