VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Python基础教程 >
  • python基础教程之C# Autofac学习笔记

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


 一、为什么使用Autofac?

    Autofac是.NET领域最为流行的IoC框架之一,传说是速度最快的一个。

    1.1、性能

    有人专门做了测试:

    1.2、优点

    1)与C#语言联系很紧密。C#里的很多编程方式都可以为Autofac使用,例如可以使用Lambda表达式注册组件。

    2)较低的学习曲线。学习它非常的简单,只要你理解了IoC和DI的概念以及在何时需要使用它们。

    3)支持JSON/XML配置。

    4)自动装配。

    5)与Asp.Net MVC集成。

    6)微软的Orchad开源程序使用的就是Autofac,可以看出它的方便和强大。

    1.3、资源

    官方网站:http://autofac.org/

    GitHub网址:https://github.com/autofac/Autofac

    学习资料:Autofac中文文档

    二、数据准备

    2.1、新建项目

    IService下的接口类:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 动物吠声接口类

    /// </summary>
    public interface IAnimalBark
    {
        /// <summary>
        /// 吠叫
        /// </summary>
        void Bark();
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 动物睡眠接口类

    /// </summary>
    public interface IAnimalSleep
    {
        /// <summary>
        /// 睡眠
        /// </summary>
        void Sleep();
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 学校接口类

    /// </summary>
    public interface ISchool
    {
        /// <summary>
        /// 放学
        /// </summary>
        void LeaveSchool();
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 学生接口类

    /// </summary>
    public interface IStudent
    {
        /// <summary>
        /// 增加学生
        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <param name="studentName">学生姓名</param>
        void Add(string studentID, string studentName);
    }
}
复制代码

    Service下的接口实现类:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 猫类
    /// </summary>
    public class Cat : IAnimalSleep
    {
        /// <summary>
        /// 睡眠
        /// </summary>
        public void Sleep()
        {
            Console.WriteLine("小猫咪睡着了zZ");
        }
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 狗类
    /// </summary>
    public class Dog : IAnimalBark, IAnimalSleep
    {
        /// <summary>
        /// 吠叫
        /// </summary>
        public void Bark()
        {
            Console.WriteLine("汪汪汪");
        }

        /// <summary>
        /// 睡眠
        /// </summary>
        public void Sleep()
        {
            Console.WriteLine("小狗狗睡着了zZ");
        }
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 学校类

    /// </summary>
    public class School : ISchool
    {
        /// <summary>
        /// IAnimalBark属性

        /// </summary>
        public IAnimalBark AnimalBark { get; set; }

        /// <summary>
        /// 放学
        /// </summary>
        public void LeaveSchool()
        {
            AnimalBark.Bark();
            Console.WriteLine("你家的熊孩子放学了⊙o⊙");
        }
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 学生类

    /// </summary>
    public class Student : IStudent
    {
        /// <summary>
        /// 无参构造函数

        /// </summary>
        public Student()
        { }

        /// <summary>
        /// 有参构造函数

        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <param name="studentName">学生姓名</param>
        public Student(string studentID, string studentName)
        {
            Add(studentID, studentName);
        }

        /// <summary>
        /// 增加学生
        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <param name="studentName">学生姓名</param>
        public void Add(string studentID, string studentName)
        {
            Console.WriteLine($"新增的学生是:{studentName}");
        }
    }
}
复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 动物摇尾巴

    /// </summary>
    public class AnimalWagging
    {
        /// <summary>
        /// IAnimalBark属性

        /// </summary>
        IAnimalBark animalBark;

        /// <summary>
        /// 有参构造函数

        /// </summary>
        /// <param name="bark">IAnimalBark变量</param>
        public AnimalWagging(IAnimalBark bark)
        {
            animalBark = bark;
        }

        /// <summary>
        /// 摇尾巴

        /// </summary>
        public virtual void Wagging()
        {
            animalBark.Bark();
            Console.WriteLine("摇尾巴");
        }

        /// <summary>
        /// 计数
        /// </summary>
        /// <returns></returns>
        public static int Count()
        {
            return 6;
        }

        /// <summary>
        /// 任务
        /// </summary>
        /// <param name="name">动物名称</param>
        /// <returns></returns>
        public virtual async Task<string> WaggingAsync(string name)
        {
            var result = await Task.Run(() => Count());
            return $"{name}摇了{result}下尾巴";
        }
    }
}
复制代码

    2.2、Autofac安装

    Client项目右键->管理 NuGet 程序包->Autofac。

    三、IoC-注册

    3.1、类型注册

    a)类型注册:使用RegisterType进行注册。

复制代码
            //注册Autofac组件
            ContainerBuilder builder = new ContainerBuilder();
            //注册实现类Student,当我们请求IStudent接口的时候,返回的是类Student的对象。
            builder.RegisterType<Student>().As<IStudent>();
            //上面这句也可改成下面这句,这样请求Student实现了的任何接口的时候,都会返回Student对象。

            //builder.RegisterType<Student>().AsImplementedInterfaces();
            IContainer container = builder.Build();
            //请求IStudent接口
            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");
复制代码

    b)类型注册(别名):假如一个接口有多个实现类,可以在注册时起别名。

复制代码
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Dog>().Named<IAnimalSleep>("Dog");
            builder.RegisterType<Cat>().Named<IAnimalSleep>("Cat");
            IContainer container = builder.Build();

            var dog = container.ResolveNamed<IAnimalSleep>("Dog");
            dog.Sleep();
            var cat = container.ResolveNamed<IAnimalSleep>("Cat");
            cat.Sleep();
复制代码

    c)类型注册(枚举):假如一个接口有多个实现类,也可以使用枚举的方式注册。

        public enum AnimalType
        {
            Dog,
            Cat
        }
复制代码
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Dog>().Keyed<IAnimalSleep>(AnimalType.Dog);
            builder.RegisterType<Cat>().Keyed<IAnimalSleep>(AnimalType.Cat);
            IContainer container = builder.Build();

            var dog = container.ResolveKeyed<IAnimalSleep>(AnimalType.Dog);
            dog.Sleep();
            var cat = container.ResolveKeyed<IAnimalSleep>(AnimalType.Cat);
            cat.Sleep();
复制代码

    3.2、实例注册

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterInstance<IStudent>(new Student());
            IContainer container = builder.Build();

            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");

    3.3、Lambda注册

    a)Lambda注册

            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new Student()).As<IStudent>();
            IContainer container = builder.Build();

            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");

    b)Lambda注册(NamedParameter)

复制代码
            ContainerBuilder builder = new ContainerBuilder();
            builder.Register<IAnimalSleep>((c, p) =>
                {
                    var type = p.Named<string>("type");
                    if (type == "Dog")
                    {
                        return new Dog();
                    }
                    else
                    {
                        return new Cat();
                    }
                }).As<IAnimalSleep>();
            IContainer container = builder.Build();

            var dog = container.Resolve<IAnimalSleep>(new NamedParameter("type", "Dog"));
            dog.Sleep();
复制代码

    3.4、程序集注册

    如果有很多接口及实现类,假如觉得这种一一注册很麻烦的话,可以一次性全部注册,当然也可以加筛选条件。

复制代码
            ContainerBuilder builder = new ContainerBuilder();
            Assembly assembly = Assembly.Load("LinkTo.Test.Autofac.Service");   //实现类所在的程序集名称
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();  //常用
            //builder.RegisterAssemblyTypes(assembly).Where(t=>t.Name.StartsWith("S")).AsImplementedInterfaces();  //带筛选

            //builder.RegisterAssemblyTypes(assembly).Except<School>().AsImplementedInterfaces();  //带筛选
            IContainer container = builder.Build();

            //单实现类的用法
            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");

            //多实现类的用法
            IEnumerable<IAnimalSleep> animals = container.Resolve<IEnumerable<IAnimalSleep>>();
            foreach (var item in animals)
            {
                item.Sleep();
            }
复制代码

    3.5、泛型注册

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof
      



  
相关教程