本文介绍Auofac,一个优秀的.NET IOC框架
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())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
3、Startup.cs 新增Autofac并初始化容器
public ILifetimeScope AutofacContainer {
get; private set; }
public void ConfigureContainer(ContainerBuilder builder)
{
}
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
IoCContainer.InitContainer(AutofacContainer);
4、新建Autofac IOC 容器类
public class IoCContainer
{
private static ILifetimeScope _container;
public static void InitContainer(ILifetimeScope autofacContainer)
{
_container = autofacContainer;
}
public static T Resolve<T>()
{
return _container.Resolve<T>();
}
}
5、新建读取配置文件工具类
public class Configs
{
private static readonly IConfiguration configuration;
static Configs()
{
configuration = IoCContainer.Resolve<IConfiguration>();
}
public static IConfigurationSection GetSection(string key)
{
return configuration.GetSection(key);
}
public static string GetConfigurationValue(string section, string key)
{
return GetSection(section)?[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;
var name = Configs.GetConfigurationValue("Setting", "Name");
}
}
以上就是.net core AutoFac的简单学习使用 + 读取配置文件的新方式的介绍,做此记录,如有帮助,欢迎点赞关注收藏!