栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.net core Autofac IOC 容器的简单使用

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.net core Autofac IOC 容器的简单使用

书接上回,介绍了.net core 读取配置文件的几种方式,本文学习Autofac的同时再次增加一种读取配置文件的方法。 本文介绍Auofac,一个优秀的.NET IOC框架 源码地址:https://github.com/autofac/Autofac 1、打开NuGet包管理器安装Autofac.Extensions.DependencyInjection包

 2、Program.cs 启用Autofac
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory()) // 启用Autofac
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            });
}
3、Startup.cs 新增Autofac并初始化容器

// 一、autofac 新增
public ILifetimeScope AutofacContainer { get; private set; }
/// 
/// 二、将内容直接注册到AutofacContainerBuilder中
/// 
/// 
public void ConfigureContainer(ContainerBuilder builder) 
{
}

// 三、autofac 新增 可选
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
IoCContainer.InitContainer(AutofacContainer);
 4、新建Autofac IOC 容器类
/// 
/// Autofac IOC 容器
/// 
public class IoCContainer 
{
	private static ILifetimeScope _container;
	/// 
	/// 初始化容器
	/// 
	/// 
	/// 
	public static void InitContainer(ILifetimeScope autofacContainer) 
	{
		_container = autofacContainer;
	}
	/// 
	/// 从容器中获取对象 Resolve an instance of the default requested type from the container
	/// 
	/// 类型
	/// 
	public static T Resolve() 
	{
		return _container.Resolve();
	}
}
5、新建读取配置文件工具类
/// 
/// 配置文件读取操作
/// 
public class Configs 
{
	private static readonly IConfiguration configuration;
	static Configs() 
	{
		configuration = IoCContainer.Resolve();
	}
	/// 
	/// 根据Key获取数配置内容
	/// 
	/// 
	/// 
	public static IConfigurationSection GetSection(string key) 
	{
		return configuration.GetSection(key);
	}
	/// 
	/// 根据section和key获取配置内容
	/// 
	/// 
	/// 
	/// 
	public static string GetConfigurationValue(string section, string key) 
	{
		return GetSection(section)?[key];
	}
	/// 
	/// 根据Key获取数据库连接字符串
	/// 
	/// 
	/// 
	public static string GetConnectionString(string key) 
	{
		return configuration.GetConnectionString(key);
	}
}
6、新建控制器,使用!读取配置的另一种方式来啦!
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase 
{
	/// 
	/// 读取内容
	/// 
	[HttpGet, HttpPost]
    public void GetContent() 
	{
		var url = Configs.GetSection("Setting:Url").Value; // http://localhost:8080/
		var name = Configs.GetConfigurationValue("Setting", "Name"); // localhost
	}
}

以上就是.net core AutoFac的简单学习使用 + 读取配置文件的新方式的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1023692.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号