AutoFac 依赖注入

参考地址:https://www.cnblogs.com/yanbigfeg/p/9855960.html

https://www.cnblogs.com/kissdodog/p/3611799.html

https://www.cnblogs.com/elvinle/p/6170294.html

调用

    internal class Program
    {
        static void Main(string[] args)
        {

            AutoFacTest facTest = new AutoFacTest();
            ContainerBuilder builder = new ContainerBuilder();
            var container = facTest.Init(builder);
            facTest.Run(container);

            Console.ReadLine();
        }
    }

实现

 public class AutoFacTest
    {
        public IContainer Init(ContainerBuilder builder)
        {
            var baseType = typeof(IDependency);
            var assbembly = AppDomain.CurrentDomain.GetAssemblies().ToList();
            builder.RegisterAssemblyTypes(assbembly.ToArray())
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                .AsImplementedInterfaces().InstancePerLifetimeScope();

            builder.RegisterType<Person2>();
            return builder.Build();
        }

        public void Run(IContainer container)
        {
            var person = container.Resolve<IPerson>();
            person.Self();
        }
    }

上面例子里面会使用到的类和接口

    /// <summary>
    /// IDependency 空的接口,所有接口继承它就进行注入
    /// </summary>
    public interface IDependency
    { }

    public interface IPerson: IDependency
    {
        void Self();
    }

    public class Person2
    {
    }

    public interface IWorker: IDependency
    {
        void Self();
    }

    public class Worker : IWorker
    {
        public void Self()
        {
            Console.WriteLine("Worker!");
        }

    }

    public interface IStudent: IDependency
    {
        void Self();
    }

    public class Student : IStudent
    {
        public void Self()
        {
            Console.WriteLine("Student!");
        }

    }

    public class Person : IPerson
    {
        public void Self()
        {
            Console.WriteLine("我叫{0}, 今年{1}岁了!", this.Name, this.Age);
        }

        //public Person()
        //{
        //    Console.WriteLine("无参构造函数");
        //}

        public Person(Person2 name, IWorker worker, IStudent student)
        {
            Console.WriteLine("多个参数构造函数");
        }

        public Person(string name)
        {
            Console.WriteLine("一个参数name构造函数");
            this.Name = name;
        }

        public int Age { get; set; }

        public string Name { get; set; }
    }

 

posted @ 2022-07-08 17:48  FH1004322  阅读(45)  评论(0编辑  收藏  举报