예제 #1
0
        private static void UseAutoFac()
        {
            //创建容器构造者,用于注册组件和服务(组件:接口实现类,服务:接口)
            ContainerBuilder builder = new ContainerBuilder();

            //注册组件UserBll类,并把服务IUserBll接口暴露给该组件
            //把服务(IUserBll)暴露给组件(UserBll)
            builder.RegisterType <UserBll>().As <IUserBll>();
            // builder.RegisterType<DogBll>().As<IAnimalBll>();//把DogBll类注册给IAnimalBll接口,注意在TestBllImpl项目中有多个IAnimalBll的实现类
            builder.RegisterType <DogBll>().Named <IAnimalBll>("Dog");
            builder.RegisterType <CatBll>().Named <IAnimalBll>("Cat");
            //创建容器
            IContainer container = builder.Build();

            //使用容器解析服务(不推荐这样,可能造成内存的泄露)
            //IUserBll userBll = container.Resolve<IUserBll>();
            //IAnimalBll dogBll = container.Resolve<IAnimalBll>();
            //使用容器的生命周期解析服务(这样可以确保服务实例被妥善地释放和垃圾回收)
            using (ILifetimeScope scope = container.BeginLifetimeScope())
            {
                IUserBll   userBll = scope.Resolve <IUserBll>();
                IAnimalBll dogBll  = scope.ResolveNamed <IAnimalBll>("Dog");
                IAnimalBll catBll  = scope.ResolveNamed <IAnimalBll>("Cat");
                userBll.Login("shanzm", "123456");
                dogBll.Cry();
                catBll.Cry();
            }
        }
예제 #2
0
        //同一个接口多个实现类,同时注册
        private static void UseAutoFac4()
        {
            ContainerBuilder builder = new ContainerBuilder();

            Assembly asm = Assembly.Load(" TestBLLImpl");

            builder.RegisterAssemblyTypes(asm).AsImplementedInterfaces();
            IContainer container = builder.Build();

            //IAnimalBll animalBll = container.Resolve<IAnimalBll>();
            //animalBll.Bark ();
            //因为在TestBLLImpl项目中有多个IAnimalBll接口的的实现类,所以这里的animalBll中具体是哪个类型的对象你也不知道
            //如果不止一个组件暴露了相同的服务, Autofac将使用最后注册的组件作为服务的提供方

            //将所有实现了IAnimalBll接口的对象都注册在一个集合中,遍历该集合分别使用每个实现了IAnimalBll接口的对象
            IEnumerable <IAnimalBll> animalBlls = container.Resolve <IEnumerable <IAnimalBll> >();

            foreach (var bll in animalBlls)
            {
                Console.WriteLine(bll.GetType());
                bll.Cry();
            }
            //挑选指定的某个实现类
            IAnimalBll dogBll = animalBlls.Where(t => t.GetType() == typeof(DogBll)).First();

            dogBll.Cry();
        }