本文主要进行Ioc容器性能对比测试。
先把代码贴上,代码很容易看明白,由于Munq编译时提示没有引用,明明添加了的,还没找到原因。
其他的测试代码后面添加。
using System; using System.Diagnostics; using System.Collections.Generic; using Autofac; using Autofac.Configuration; using Microsoft.Practices.Unity; //using Munq; namespace AutofacDemo { class Program { const long iterations = 10000; private static List<Test> ts = new List<Test> { new UnityTest(), new AutofacTest() }; static void Main(string[] args) { Console.WriteLine("Running {0} iterations", iterations); Console.WriteLine("{0,12}: {1,12} - {2,12} ", "Test Name", "Ticks", "mSec"); Console.WriteLine("-------------------------------------------------------"); ts.ForEach(c => Measure(c)); Console.Read(); } private static void Measure(Test t) { GC.Collect(); var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < iterations; i++) { t.Run(); } stopwatch.Stop(); var ticks = stopwatch.ElapsedTicks; Console.WriteLine("{0,12}: {1,12:N0} - {2,12:N2} ", t.GetType().Name, ticks, ticks * 1000 / Stopwatch.Frequency); } } abstract class Test { public abstract void Run(); } //public class MunqTest : Test //{ // public override void Run() // { // //step 1: create a container // IocContainer container = new IocContainer(); // //step 2: regesiter interface as a type // container.Register<IDal, OracleDal>(); // container.Resolve<IDal>().save(); // } //} class UnityTest:Test { static IUnityContainer container; static UnityTest() { //step 1: create a container container = new UnityContainer(); //step 2: regesiter interface as a type container.RegisterType(typeof(IDal), typeof(OracleDal)); } public override void Run() { container.Resolve<IDal>().save(); } } class AutofacTest:Test { static IContainer container; static AutofacTest() { var builder = new ContainerBuilder(); builder.Register<IDal>(c => new OracleDal()).SingleInstance(); container = builder.Build(); } public override void Run() { container.Resolve<IDal>().save(); } } interface IDal { void save(); } interface ILog { } class OracleDal : IDal { public void save() { //Console.WriteLine("SqlServer save."); } } class OracleDal2 : IDal { public ILog log { get; private set; } public OracleDal2(ILog log) { this.log = log; } public void save() { // Console.WriteLine("Oracle save."); } } }