AutoFac 简单好用的IOC


0. 安装autofac的nuget




1. 准备測试接口和类


class BallGame : IPlay
    {
        public void Do()
        {
            Console.WriteLine("ball game");
            Console.Read();
        }
    }


    class ComputerGame : IPlay
    {
        public void Do()
        {
            Console.WriteLine("computer game.");
            Console.Read();
        }
    }


    interface IPlay
    {
        void Do();
    }



2. 编写autofac模块
class PlayModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType(typeof(ComputerGame)).As(typeof(IPlay)).InstancePerLifetimeScope();
        }
    }




这种设计是主张模块化编程。把职责隔离到不同的dll,这样之后更新起来仅仅须要替代指定dll就可以。


3. 注冊autofac模块。执行測试


var builder = new ContainerBuilder();
builder.RegisterModule(new PlayModule());
var container = builder.Build();
//container.Resolve<IPlay>().Do();
using (var scope = container.BeginLifetimeScope())
{
      var play = scope.Resolve<IPlay>();
      play.Do();
}



先创建一个builder。然后注冊模块,最后builder调用Build函数返回container对象。
接下来能够选择性的控制对象的生命周期。




4.完毕測试。

原文地址:https://www.cnblogs.com/wgwyanfs/p/7141242.html