Example #1
0
        //一个实现类实现了多个接口
        private static void UseAutoFac2()
        {
            ContainerBuilder builder = new ContainerBuilder();

            //MasterBll实现了多个接口,我们可以把该类注册给他所有实现的接口
            //换言之,只要是MasterBll实现的接口,我们都可以该他一个MasterBll类型的对象
            //但是注意,这个MasterBll对象只包含当前接口的方法


            builder.RegisterType <MasterBll>().AsImplementedInterfaces();//把MasterBll类注册给所有他实现的接口
            //即一个组件暴露了多个服务,这里就等价于:
            //builder.RegisterType<MasterBll>().As<IUserBll>().As<IMasterBll>();

            IContainer container = builder.Build();

            IUserBll userBll = container.Resolve <IUserBll>(); //其实这里的userBll是MasterBll类型的对象,但是只具有IUserBll接口中的方法

            userBll.Login("shanzm", "11111");                  //打印:登录用户是Master:shanzm
            Console.WriteLine(userBll.GetType());              //打印:TestBLLImpl.MasterBll
        }
Example #2
0
        //把所有的接口实现类都注册
        private static void UseAutoFac3()
        {
            //从上面几个示例,你可以发现好像使用依赖反转,好像有点麻烦!
            //若是TestBLL中有许多类,需要注册,则就可以显示出使用控制反转的
            ContainerBuilder builder = new ContainerBuilder();

            Assembly asm = Assembly.Load(" TestBLLImpl");                 //把TestBLLImpl程序集中的所有类都是注册给他的接口

            builder.RegisterAssemblyTypes(asm).AsImplementedInterfaces(); //注意RegisterAssemblyTypes()的参数可以是多个程序集
            IContainer container = builder.Build();
            //其实到这里你就会发现使用AutoFac的便利了,
            //你需要在TestIBLL项目中给定义每个接口,在TestBllImpl项目中去实现每个接口
            //在TestUI项目中就不需要像以前一样去实例每一个TestBLLImpl项目中的类,使用AutoFac把每个类注册给他的接口
            //然后直接调用接口对象就可以了,而且你都不用明白到底是哪个一个类实现该接口
            //从而实现了解耦


            IUserBll userBll = container.Resolve <IUserBll>();

            userBll.Login("shanzm", "123456");

            Console.WriteLine(userBll.GetType());//调试时查看uerBll接口对象中的具体实现对象:TestBllImpl.UserBll
        }