Autofac IContainer 测试

using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutofacDemo
{
    public interface ITest
    {
        string Hello1();
    }

    public class Test1 : ITest
    {
        public string Hello1()
        {
            Console.WriteLine("ok1");
            return "ok11";
        }
    }

    public class Test2 : ITest
    {
        public string Hello1()
        {
            Console.WriteLine("ok2");
            return "ok22";
        }
    }

    class Program
    {
        private static IContainer Container1 { get; set; }
        private static IContainer Container2 { get; set; }

        static void Main(string[] args)
        {
            var builder3 = new ContainerBuilder();
            builder3.RegisterType<Test1>().As<ITest>();
            var Container3 = builder3.Build();

            var builder1 = new ContainerBuilder();
            builder1.RegisterType<Test1>().As<ITest>();
            var Container1 = Container3;// builder1.Build();

            var builder2 = new ContainerBuilder();
            builder2.RegisterType<Test2>().As<ITest>();
            var Container2 = Container3;// builder2.Build();

            //using (var scope = Container1.BeginLifetimeScope())
            //{
            //    var test1 = scope.Resolve<ITest>();
            //    test1.Hello1();
            //}

            //using (var scope = Container2.BeginLifetimeScope())
            //{
            //    var test2 = scope.Resolve<ITest>();
            //    test2.Hello1();
            //}

            var test1 = Container1.Resolve<ITest>();
            test1.Hello1();

            var test2 = Container2.Resolve<ITest>();
            test2.Hello1();
            Console.WriteLine(Container1.GetHashCode());
            Console.WriteLine(Container2.GetHashCode());
        }
    }
}

结果是这两个hashcode相等

Console.WriteLine(Container1.GetHashCode());
Console.WriteLine(Container2.GetHashCode());
原文地址:https://www.cnblogs.com/shiningrise/p/5568885.html