AutoFac在项目中的应用

时间:2022-05-07
本文章向大家介绍AutoFac在项目中的应用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

技能大全:http://www.cnblogs.com/dunitian/p/4822808.html#skill

完整Demo:https://github.com/dunitian/LoTCodeBase/tree/master/NetCode/3.常用技能/8.AutoFac/1.AutoFac

先看效果

IBLL

IBLL

核心代码:

代码附件:

 public ActionResult Index()
 {
 ITestBLL testBLL = Container.Resolve<ITestBLL>();
 ViewBag.Name = testBLL.GetName();
 return View();
 }
 
————————————————————————————————
 
 public interface ITestBLL
 {
 string GetName();
 }
 
————————————————————————————————
 
 public class TestBLL : ITestBLL
 {
 public string GetName()
 {
 return "我为NET狂-官方群① 238575862";
 }
 }
 
————————————————————————————————
 
/// <summary>
/// Autofac IOC类
/// </summary>
public class Container
{
 /// <summary>
 /// IOC 容器
 /// </summary>
 public static IContainer container = null;
 public static T Resolve<T>()
 {
 try
 {
 if (container == null)
 {
 Initialise();
 }
 }
 catch (Exception ex)
 {
 throw new Exception("IOC实例化出错!" + ex.Message);
 }
 
 return container.Resolve<T>();
 }
 
 /// <summary>
 /// 初始化
 /// </summary>
 public static void Initialise()
 {
 var builder = new ContainerBuilder();
 
 //格式:builder.RegisterType<xxxx>().As<Ixxxx>().InstancePerLifetimeScope();
 builder.RegisterType<TestBLL>().As<ITestBLL>().InstancePerLifetimeScope();
 
 container = builder.Build();
 }
}