AutoFac在项目中的应用

时间:2021-09-28 20:39:59

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

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

先看效果

AutoFac在项目中的应用

IBLL

AutoFac在项目中的应用

IBLL

AutoFac在项目中的应用

核心代码:

AutoFac在项目中的应用

 AutoFac在项目中的应用

代码附件:

        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();
    }
}

扩展:http://blog.csdn.net/dhx20022889/article/details/9061483