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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM