Autofac IContainer 测试

Posted 吴晓阳

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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());

以上是关于Autofac IContainer 测试的主要内容,如果未能解决你的问题,请参考以下文章

带有 Autofac 单元测试 DataContext 的实体框架 6

转载:xuggle学习-IContainer2

我们啥时候应该为组件实现带有 IContainer 参数的构造函数?

.net webapi+autofac+autoMapper 单元测试

java.lang.NoClassDefFoundError: org/eclipse/core/resources/IContainer

Autofac 通过 PreserveExistingDefaults 解决单元测试 Fake 对象被覆盖