public void RegisterType <F, T>(params object[] members) where T : F { lock (this.container) { UnityContainerExtensions.RegisterType <F, T>(this.container, this.ToObjects <InjectionMember>(members)); } }
/// <summary> /// Gets the entity instance. /// </summary> /// <typeparam name="T">The entity contract.</typeparam> /// <returns>The entity instance.</returns> public virtual T GetConfiguration <T>() where T : class { var entityName = string.Format("{0}_{1}", Sitecore.Context.Site.Name, Sitecore.Context.Database.Name); try { var args = new ConfigurationPipelineArgs(typeof(T)) { EntityName = entityName }; CorePipeline.Run("getConfiguration", args); Assert.IsNotNull(args.ConfigurationItem, typeof(T), "Unable to resolve '\"{0}\"' configuration.", typeof(T).Name); this.innerContainer.RegisterInstance(entityName, (T)args.ConfigurationItem); return((T)args.ConfigurationItem); } catch (Exception exception) { Log.Warn(exception.Message, exception); lock (this) { return(UnityContainerExtensions.Resolve <T>(this)); } } }
public static T GetBusinessInstance <T>(params KeyValuePair <string, object>[] ParamsBatch) { T BusinessInstance = default(T); IUnityContainer container = new UnityContainer(); container.AddNewExtension <Interception>(); if (ParamsBatch.Count() > 0) { container.RegisterType(typeof(T), new Interceptor <TransparentProxyInterceptor>(), new InterceptionBehavior <BusinessServiceBehavior>()); var ResolverOverrideBatch = new ResolverOverride[ParamsBatch.Count()]; for (int i = 0; i < ParamsBatch.Count(); i++) { ResolverOverrideBatch[i] = new ParameterOverride(ParamsBatch[i].Key, ParamsBatch[i].Value); } BusinessInstance = container.Resolve <T>(ResolverOverrideBatch); } else { container.RegisterType(typeof(T), new Interceptor <TransparentProxyInterceptor>(), new InterceptionBehavior <BusinessServiceBehavior>(), new InjectionConstructor()); BusinessInstance = UnityContainerExtensions.Resolve <T>(container); } return(BusinessInstance); }
/// <summary> /// Ons the resume. /// </summary> protected override void OnResume() { base.OnResume(); var lifecycleService = UnityContainerExtensions.Resolve <ILifecycleService>(this.Container); lifecycleService.StartOnResume(this.NavigationService); }
public void RegisterInstance <T>(string name, T instance) { lock (this.container) { UnityContainerExtensions.RegisterInstance <T>(this.container, name, instance); } }
public void RegisterTypeWithConstructor <T>(string name, int lifecycle, params object[] constructors) { lock (this.container) { UnityContainerExtensions.RegisterType <T>(this.container, name, this.GetLifetimeManager(lifecycle), this.ToObjects <InjectionConstructor>(constructors)); } }
public bool IsRegistered(Type type, string name) { lock (this.container) { return(UnityContainerExtensions.IsRegistered(this.container, type, name)); } }
public void RegisterTypeWithConstructor <T>(string name, params object[] constructors) { lock (this.container) { UnityContainerExtensions.RegisterType <T>(this.container, name, this.ToObjects <InjectionConstructor>(constructors)); } }
public void RegisterType(Type from, Type to, string name, params object[] members) { lock (this.container) { UnityContainerExtensions.RegisterType(this.container, from, to, name, this.ToObjects <InjectionMember>(members)); } }
public void RegisterType <F, T>(string name, int lifecycle, params object[] members) where T : F { lock (this.container) { UnityContainerExtensions.RegisterType <F, T>(this.container, name, this.GetLifetimeManager(lifecycle), this.ToObjects <InjectionMember>(members)); } }
//public static T Instance<T>() where T : class //{ // Func<Type, bool> func = null; // if (!UnityContainerExtensions.IsRegistered<T>(IFactory.iunityContainer_0)) // { // bool flag = false; // try // { // object obj; // Monitor.Enter(obj = IFactory.object_0, ref flag); // Assembly assembly = typeof(T).Assembly; // Class2 @class = Class2.smethod_0(assembly); // if (@class.method_0() != null) // { // foreach (ContainerRegistration current in @class.method_0().Registrations) // { // if (!UnityContainerExtensions.IsRegistered(IFactory.iunityContainer_0, current.RegisteredType)) // { // UnityContainerExtensions.RegisterType(IFactory.iunityContainer_0, current.RegisteredType, current.MappedToType, new InjectionMember[0]); // } // } // } // string bllSuffix = ".BLL"; // IEnumerable<Type> arg_DB_0 = assembly.GetTypes(); // if (func == null) // { // func = new Func<Type, bool>(IFactory.smethod_0<T>); // } // IEnumerable<Type> enumerable = from type in arg_DB_0.Where(func) // where type.BaseType != null && type.BaseType.IsGenericType && !type.IsInterface && typeof(T).IsAssignableFrom(type) && type.Namespace.EndsWith(bllSuffix) // select type; // foreach (Type current2 in enumerable) // { // UnityContainerExtensions.RegisterType(IFactory.iunityContainer_0, typeof(T), current2, new InjectionMember[0]); // } // } // finally // { // if (flag) // { // object obj=0; // Monitor.Exit(obj); // } // } // } // return UnityContainerExtensions.Resolve<T>(IFactory.iunityContainer_0, new ResolverOverride[0]); // Func<Type, bool> predicate = null; // if (!iunityContainer_0.IsRegistered<T>()) // { // lock (object_0) // { // Assembly assembly = typeof(T).Assembly; // Class2 class3 = Class2.smethod_0(assembly); // if (class3.method_0() != null) // { // foreach (ContainerRegistration registration in class3.method_0().Registrations) // { // if (!UnityContainerExtensions.IsRegistered(iunityContainer_0, registration.RegisteredType)) // { // UnityContainerExtensions.RegisterType(iunityContainer_0, registration.RegisteredType, registration.MappedToType, new InjectionMember[0]); // } // } // } // string bllSuffix = ".BLL"; // if (predicate == null) // { // predicate = new Func<Type, bool>(IFactory.smethod_0<T>); // } // foreach (Type type in from type in assembly.GetTypes().Where<Type>(predicate) // where (((type.BaseType != null) && type.BaseType.IsGenericType) && (!type.IsInterface && typeof(T).IsAssignableFrom(type))) && type.Namespace.EndsWith(bllSuffix) // select type) // { // UnityContainerExtensions.RegisterType(iunityContainer_0, typeof(T), type, new InjectionMember[0]); // } // } // } // return iunityContainer_0.Resolve<T>(new ResolverOverride[0]); //} public static T Instance <T>() where T : class { Func <Type, bool> predicate = null; if (!iunityContainer_0.IsRegistered <T>()) { lock (object_0) { Assembly assembly = typeof(T).Assembly; Class2 class3 = Class2.smethod_0(assembly); if (class3.method_0() != null) { foreach (ContainerRegistration registration in class3.method_0().Registrations) { if (!UnityContainerExtensions.IsRegistered(iunityContainer_0, registration.RegisteredType)) { UnityContainerExtensions.RegisterType(iunityContainer_0, registration.RegisteredType, registration.MappedToType, new InjectionMember[0]); } } } string bllSuffix = ".BLL"; if (predicate == null) { predicate = new Func <Type, bool>(IFactory.smethod_0 <T>); } foreach (Type type in from type in assembly.GetTypes().Where <Type>(predicate) where (((type.BaseType != null) && type.BaseType.IsGenericType) && (!type.IsInterface && typeof(T).IsAssignableFrom(type))) && type.Namespace.EndsWith(bllSuffix) select type) { UnityContainerExtensions.RegisterType(iunityContainer_0, typeof(T), type, new InjectionMember[0]); } } } return(iunityContainer_0.Resolve <T>(new ResolverOverride[0])); }
public void RegisterType <T>(int lifecycle, params object[] members) { lock (this.container) { UnityContainerExtensions.RegisterType <T>(this.container, this.GetLifetimeManager(lifecycle), this.ToObjects <InjectionMember>(members)); } }
private PolicyDefinition UpdateRuleDrivenPolicyInjection() { UnityContainerExtensions.RegisterType <InjectionPolicy, RuleDrivenPolicy>(_extension.Container, _policyName, new InjectionConstructor(_policyName, new ResolvedArrayParameter <IMatchingRule>(_rulesParameters.ToArray()), _handlersNames.ToArray())); return(this); }
public void TestStandardRegistrars() { var container = new UnityContainer(); var configurator = new PollingHostConfigurator(container); configurator.StandardRegistrars(); var candidate = UnityContainerExtensions.Resolve <IContainerRegistrar>(container, typeof(PollingHostRegistrar).FullName); Assert.AreEqual(typeof(PollingHostRegistrar), candidate.GetType()); }
protected override void OnInitialized() { InitializeComponent(); InitializeMapper(); NavigationService.NavigateAsync("ExtendedLoadingPage"); var lifecycleService = UnityContainerExtensions.Resolve <ILifecycleService>(this.Container); lifecycleService.StartAsync(this.NavigationService); SetResources(); }
public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType <IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType <IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType <IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType <IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow <ArgumentNullException>(); } }
public object Resolve(Type t, string name) { object obj2; try { obj2 = ((t.IsClass && !t.IsAbstract) || UnityContainerExtensions.IsRegistered(this._container, t, name)) ? this._container.Resolve(t, name, new ResolverOverride[0]) : null; } catch (ResolutionFailedException exception) { throw new InvalidOperationException(string.Format("实例化类型失败,类型为:{0},名称为:{1}", t, name), (Exception)exception); } return(obj2); }
public static void RegisterTypes(IUnityContainer container) { InjectionConstructor injectionConstructor = new InjectionConstructor(new object[1] { (object)ConfigurationManager.ConnectionStrings["YmatouStaticContentConnectionString"].ConnectionString }); if (null == HttpContext.Current) { UnityContainerExtensions.RegisterType <StaticContentQueryDataContext, StaticContentQueryDataContext>(container, (LifetimeManager) new ContainerControlledLifetimeManager(), new InjectionMember[1] { (InjectionMember)injectionConstructor }); } else { UnityContainerExtensions.RegisterType <StaticContentQueryDataContext, StaticContentQueryDataContext>(container, (LifetimeManager) new HttpContextLifetimeManager <StaticContentQueryDataContext>(), new InjectionMember[1] { (InjectionMember)injectionConstructor }); } UnityContainerExtensions.RegisterType <IStaticContentQueryService, StaticContentQueryService>(container, new InjectionMember[0]); }
private void RegisterMapping(Mapping mapping, bool writeOver) { if (string.IsNullOrEmpty(mapping.Name)) { if (!writeOver && UnityContainerExtensions.IsRegistered(this._container, mapping.From)) { throw new Exception($"Já existe registro de mapeamento para este tipo ( {mapping.From.FullName} ), verifique o tipo ou faça o registro explicitando um nome."); } InjectionMember[] injectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapping.From, mapping.To, injectionMembers); } else { if (!writeOver && UnityContainerExtensions.IsRegistered(this._container, mapping.From)) { throw new Exception($"Já existe registro de mapeamento nomeado para este tipo ( {mapping.From.FullName} ), verifique o tipo."); } InjectionMember[] injectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapping.From, mapping.To, mapping.Name, injectionMembers); } }
private void RegistrarMapeamento(Mapeamento mapeamento, bool sobreescrever) { if (string.IsNullOrEmpty(mapeamento.Nome)) { if (!sobreescrever && UnityContainerExtensions.IsRegistered(this._container, mapeamento.De)) { throw new Exception($"Já existe registro de mapeamento para este tipo ( {mapeamento.De.FullName} ), verifique o tipo ou faça o registro explicitando um nome."); } InjectionMember[] memberArray1 = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapeamento.De, mapeamento.Para, memberArray1); } else { if (!sobreescrever && UnityContainerExtensions.IsRegistered(this._container, mapeamento.De)) { throw new Exception($"Já existe registro de mapeamento nomeado para este tipo ( {mapeamento.De.FullName} ), verifique o tipo."); } InjectionMember[] memberArray2 = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapeamento.De, mapeamento.Para, mapeamento.Nome, memberArray2); } }
private static void smethod_1(IUnityContainer iunityContainer_1, Assembly assembly_0) { Dictionary <string, Type> dictionary = new Dictionary <string, Type>(); Dictionary <string, Type> dictionary2 = new Dictionary <string, Type>(); string value = ".DAL"; string value2 = ".IDAL"; Type[] types = assembly_0.GetTypes(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; string @namespace = type.Namespace; if (!string.IsNullOrEmpty(@namespace)) { if (type.IsInterface && @namespace.EndsWith(value2)) { if (!dictionary.ContainsKey(type.FullName)) { dictionary.Add(type.FullName, type); } } else if (@namespace.EndsWith(value) && !dictionary2.ContainsKey(type.FullName)) { dictionary2.Add(type.FullName, type); } } } foreach (string current in dictionary.Keys) { Type type2 = dictionary[current]; foreach (string current2 in dictionary2.Keys) { Type type3 = dictionary2[current2]; if (type2.IsAssignableFrom(type3)) { UnityContainerExtensions.RegisterType(iunityContainer_1, type2, type3, new InjectionMember[0]); } } } }
public T ObterInstanciaDe <T>(string nome, params ISobrescreverMapeamento[] parametros) { T local2; try { T local; ResolverOverride[] overrideArray = BuildParameters(parametros); if (string.IsNullOrEmpty(nome)) { local = (overrideArray == null) ? UnityContainerExtensions.Resolve <T>(this._container, new ResolverOverride[0]) : UnityContainerExtensions.Resolve <T>(this._container, overrideArray); } else { local = (overrideArray == null) ? UnityContainerExtensions.Resolve <T>(this._container, nome, new ResolverOverride[0]) : UnityContainerExtensions.Resolve <T>(this._container, nome, overrideArray); } local2 = local; } catch (Exception exception) { throw new Exception($"Ocorreu erro ao tentar obter o tipo {typeof(T).Name}, verifique o injetor.", exception); } return(local2); }
/// <summary> /// Accepts additional parameters and runs the tests inside the given class /// </summary> /// <typeparam name="T">The type of class that contains the tests</typeparam> private static void RunTests <T>() { if (typeof(T) != typeof(IPlacementAlgorithm) && typeof(T) != typeof(IMinimumBoundingBoxFinder)) { throw new NotSupportedException(); } string str = ""; IImageSorter selectedImageSorter = null; IPlacementAlgorithm selectedPlacementAlgorithm = null; //Ask the user to select an image sorter that will parametrize the placement algorithm / minimum bounding box finder while (true) { do { Console.WriteLine("Select image sorter to be used: "); Console.WriteLine($"\tEnter 'a' to select {typeof(ByHeightAndWidthImageSorter).Name}"); Console.WriteLine($"\tEnter 'b' to select {typeof(ByHeightAndWidthImageSorterDesc).Name}"); Console.WriteLine($"\tEnter 'c' to select {typeof(PreserveOrderImageSorter).Name}"); } while ((str = Console.ReadLine()).Length != 1); switch (str[0]) { case 'a': selectedImageSorter = new ByHeightAndWidthImageSorter(); break; case 'b': selectedImageSorter = new ByHeightAndWidthImageSorterDesc(); break; case 'c': selectedImageSorter = new PreserveOrderImageSorter(); break; default: continue; } break; } //If the users wants to benchmark Minimum bounding box finders // then ask the user to select an placement algorithm that will parametrize tminimum bounding box finders if (typeof(T) == typeof(IMinimumBoundingBoxFinder)) { while (true) { do { Console.WriteLine("Select placement algorithm to be used: "); Console.WriteLine($"\tEnter 'a' to select {typeof(BLAlgorithmPacker).Name}"); Console.WriteLine($"\tEnter 'b' to select {typeof(SkylineAlgorithm).Name}"); Console.WriteLine($"\tEnter 'c' to select {typeof(MaximalRectanglesAlgorithm).Name}"); } while ((str = Console.ReadLine()).Length != 1); switch (str[0]) { case 'a': selectedPlacementAlgorithm = new BLAlgorithmPacker(); break; case 'b': selectedPlacementAlgorithm = new SkylineAlgorithm(); break; case 'c': selectedPlacementAlgorithm = new MaximalRectanglesAlgorithm(); break; default: continue; } break; } } bool isItSquaresTest = true; int numOfRects = 0; int seed = 0; //Ask the user to select test type //Currently, two types of tests are implemented (differing in the input sequence) // 1) Input sequence consisting of n squares with sizes 1x1, ..., nxn (given in random order) // 2) Input sequence consisting of n rectangles with random (but upper-bounded) sizes (given in random order) while (true) { str = ""; do { Console.WriteLine("Select test type:"); Console.WriteLine("\tEnter 'a' to perform test with squares of sizes 1x1, 2x2, ..., nxn"); Console.WriteLine("\tEnter 'b' to perform test with n rectangles of random sizes"); } while ((str = Console.ReadLine()).Length != 1); switch (str[0]) { case 'b': case 'a': isItSquaresTest = str[0] == 'a'; //Ask the user to enter number of rectangles/squares while (true) { Console.WriteLine("\tEnter number of 'n' - rectangles(squares)"); str = Console.ReadLine(); if (Int32.TryParse(str, out numOfRects)) { if (numOfRects > 0) { break; } } } //If it is the random rectangles test then ask the user to enter the random seed // The seed will be user to construct the random generator used to generate the random rectangle sizes if (!isItSquaresTest) { while (true) { Console.WriteLine("\tEnter seed"); str = Console.ReadLine(); if (Int32.TryParse(str, out seed)) { break; } } } break; default: continue; } break; } //Now when the user has selected the type of test and all the parameters // It is time to actaully run the tests. But because we need to test types // that are contained within plugins and also because BenchmarkDotNet (in a standard scenario) // requires to use (static) attribute [Benchmark] on the methods that should be called // we have decided to generate the benchmark class (with benchmark methods) dynamically at runtime // and then compile the generated class and pass the type of this class to the BenchmarkRunner string assemblyName = Path.GetRandomFileName(); //Assemblies referenced by the assembly that will be generated at runtime //For each type that will be used in the generated test, an assembly containing //the used type has to be loaded var references = new List <MetadataReference>() { MetadataReference.CreateFromFile(typeof(BenchmarkDotNet.Attributes.BenchmarkAttribute).Assembly.Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.CSharp")).Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("netstandard")).Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Unity.Container")).Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Unity.Abstractions")).Location), MetadataReference.CreateFromFile(typeof(IMinimumBoundingBoxFinder).Assembly.Location), MetadataReference.CreateFromFile(typeof(TestUtil).Assembly.Location), MetadataReference.CreateFromFile(typeof(CancellationToken).Assembly.Location), MetadataReference.CreateFromFile(typeof(UnityContainerExtensions).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), MetadataReference.CreateFromFile(typeof(Random).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Collections.Concurrent.ConcurrentDictionary <string, int>).Assembly.Location), MetadataReference.CreateFromFile(typeof(ValueTuple <long, long>).Assembly.Location) }; //Create same IoC here and in the generated class //This is because inside this class we try if (using the same IoC container with same registrations) //a given type could be resolved and if it does not, we exclude benchmark for this type in the generated class using UnityContainer IoC = new UnityContainer(); IoC.RegisterFactory <IImageSorter>(_ => selectedImageSorter); if (selectedPlacementAlgorithm != null) { IoC.RegisterFactory <IPlacementAlgorithm>(_ => selectedPlacementAlgorithm); } //The generated source var benchmarkClassTemplate = new StringBuilder(); //Using statements benchmarkClassTemplate.AppendLine("using System;"); benchmarkClassTemplate.AppendLine("using Unity;"); benchmarkClassTemplate.AppendLine("using System.Linq;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.MBBF;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.Placement;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.Sorting;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.Placement.Skyline;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.Placement.Guillotine;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Core.Packing.Placement.MaximalRectangles;"); benchmarkClassTemplate.AppendLine("using System.Collections.Generic;"); benchmarkClassTemplate.AppendLine("using System.Threading;"); benchmarkClassTemplate.AppendLine("using PaunPacker.Tests;"); //Beginning of the class benchmarkClassTemplate.AppendLine($"public class {typeof(T).Name}Benchmarks"); benchmarkClassTemplate.AppendLine("{"); //Member declarations benchmarkClassTemplate.AppendLine(@" private static UnityContainer IoC { get; set; } private static Random rnd; private static List<PaunPacker.Core.Types.PPRect> randomRects; static System.Collections.Concurrent.ConcurrentDictionary<string, ValueTuple<long, long>> results; "); benchmarkClassTemplate.AppendLine($"\n\tstatic {typeof(T).Name}Benchmarks()"); benchmarkClassTemplate.AppendLine("\t{"); //Constructor code benchmarkClassTemplate.AppendLine($@" IoC = new UnityContainer(); IoC.RegisterInstance<IImageSorter>(new {selectedImageSorter.GetType().Name}()); results = new System.Collections.Concurrent.ConcurrentDictionary<string, ValueTuple<long, long>>(); rnd = new Random(" + seed + @"); randomRects = new List<PaunPacker.Core.Types.PPRect>(" + numOfRects + @"); int dimensionBound = Int32.MaxValue / " + numOfRects + @"; dimensionBound = dimensionBound > 2049 ? 2049 : dimensionBound; for (int i = 0; i < " + numOfRects + @"; i++) { randomRects.Add(new PaunPacker.Core.Types.PPRect(0, 0, rnd.Next(1, dimensionBound), rnd.Next(1, dimensionBound))); } "); if (selectedPlacementAlgorithm != null) { benchmarkClassTemplate.AppendLine($"IoC.RegisterInstance<IPlacementAlgorithm>(new { selectedPlacementAlgorithm.GetType().Name }());"); } benchmarkClassTemplate.AppendLine("\t}"); //Constructor ends here if (isItSquaresTest) { benchmarkClassTemplate.AppendLine($@" [BenchmarkDotNet.Attributes.ParamsSourceAttribute(nameof(ValuesForN))] public int N; public IEnumerable<int> ValuesForN => System.Linq.Enumerable.Range(1, {numOfRects}); "); } int numOfTests = 0; // We are testing minimum bounding box finders, so generate tests for them if (selectedPlacementAlgorithm != null) { foreach (var x in MinimumBoundingBoxFinderTypes) { try { UnityContainerExtensions.Resolve(IoC, Type.GetType(x.AssemblyQualifiedName), null); references.Add(MetadataReference.CreateFromFile(x.Assembly.Location)); benchmarkClassTemplate.AppendLine("\t[BenchmarkDotNet.Attributes.BenchmarkAttribute]"); benchmarkClassTemplate.AppendLine($"\tpublic void Test{x.Name}()"); benchmarkClassTemplate.AppendLine("{"); benchmarkClassTemplate.AppendLine($"\tvar x = Type.GetType(\"{x.AssemblyQualifiedName}\");"); benchmarkClassTemplate.AppendLine($"\tvar res = (UnityContainerExtensions.Resolve(IoC, x, null) as IMinimumBoundingBoxFinder).FindMinimumBoundingBox(TestUtil.Shuffle(" + (isItSquaresTest ? "TestUtil.GetIncreasingSquares(N)" : $"randomRects") + "), CancellationToken.None);"); benchmarkClassTemplate.AppendLine($"results.AddOrUpdate(\"Test{x.Name}\", (res.Width * res.Height, 1), (key, old) => ((long)(old.Item1 + (double)(res.Width * res.Height - old.Item1) / (double)(old.Item2 + 1)), old.Item2 + 1));"); benchmarkClassTemplate.AppendLine("}"); benchmarkClassTemplate.AppendLine(); numOfTests++; } catch (ResolutionFailedException) { //Do not add benchmark for types that could not be resolved (for example types that are extensible by other plugins // via plugin view ...). These types will simply not be benchmarked. } } } else { foreach (var x in PlacementAlgorithmTypes) { try { UnityContainerExtensions.Resolve(IoC, Type.GetType(x.AssemblyQualifiedName), null); references.Add(MetadataReference.CreateFromFile(x.Assembly.Location)); benchmarkClassTemplate.AppendLine("\t[BenchmarkDotNet.Attributes.BenchmarkAttribute]"); benchmarkClassTemplate.AppendLine($"\tpublic void Test{x.Name}()"); benchmarkClassTemplate.AppendLine("{"); benchmarkClassTemplate.AppendLine($"\tvar x = Type.GetType(\"{x.AssemblyQualifiedName}\");"); benchmarkClassTemplate.AppendLine($"\tvar res = (UnityContainerExtensions.Resolve(IoC, x, null) as IPlacementAlgorithm).PlaceRects(Int32.MaxValue, Int32.MaxValue, TestUtil.Shuffle(" + (isItSquaresTest ? "TestUtil.GetIncreasingSquares(N)" : $"randomRects") + "));"); benchmarkClassTemplate.AppendLine("long actualW = res.Rects.Max(y => y.Right); long actualH = res.Rects.Max(y => y.Bottom);"); benchmarkClassTemplate.AppendLine($"checked {{ results.AddOrUpdate(\"Test{x.Name}\", (actualW * actualH, 1), (key, old) => ((long)(old.Item1 + (double)(actualW * actualH - old.Item1) / (double)(old.Item2 + 1)), old.Item2 + 1));"); benchmarkClassTemplate.AppendLine("}}"); benchmarkClassTemplate.AppendLine(); numOfTests++; } catch (ResolutionFailedException) { //Do not add benchmark for types that could not be resolved (for example types that are extensible by other plugins // via plugin view ...). These types will simply not be benchmarked. } } } //Global cleanup method //Because BenchmarkDotNet does not allow to report benchmark methods return values //We had to "hack" around it by using these two methods //And save the method results inside a file and then (when showing the report) load it from the file //The GlobalCleanup should not be measured as a part of the benchmark //However we still need to somewhere remember the return value of the methods //Because writing to file in the benchmark method itself would totally kill the performance, we have decided to store it in dictionary //Which still causes some test distortion but it should be OK (all the tests use it so their base-line is just shifted) benchmarkClassTemplate.AppendLine(@" [BenchmarkDotNet.Attributes.GlobalCleanup] public void GlobalCleanup() { //We want to call it only once, not after every [Benchmark] method if (results.Count() == " + numOfTests + @") { using (var sw = new System.IO.StreamWriter(""results.txt"", true)) { //foreach (var r in randomRects) //for debug purposes // sw.WriteLine(r.Width + ""x"" + r.Height); foreach (var res in results) sw.WriteLine(res.Key + "";"" + res.Value.Item1 + "";"" + res.Value.Item1 + "";"" + res.Value.Item2); } results.Clear(); } } "); benchmarkClassTemplate.AppendLine("}"); //Benchmark class ends here Console.WriteLine("Please wait ... (Compiling the Benchmarks)"); //Create syntax tree and compile it SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(benchmarkClassTemplate.ToString()); CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release)); //Emit the CIL into memory stream using var ms = new MemoryStream(); EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Microsoft.CodeAnalysis.Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Microsoft.CodeAnalysis.Diagnostic diagnostic in failures) { Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); Type type = assembly.GetType($"{typeof(T).Name}Benchmarks"); Console.WriteLine("Starting the Benchmarks"); var x = BenchmarkDotNet.Running.BenchmarkRunner.Run(type, new Config()); Console.WriteLine("Done"); } }
/// <summary> /// 注册抽象类型与具体实现的类型 /// </summary> /// <param name="from">接口类型</param> /// <param name="to">具体类型</param> public void RegisterType(Type from, Type to) { UnityContainerExtensions.RegisterType(this, from, to); }
/// <summary> /// 类型是否被注册到IoC容器 /// </summary> /// <param name="type"></param> /// <returns></returns> public bool IsRegistered(Type type) { return(UnityContainerExtensions.IsRegistered(this, type)); }
/// <summary> /// 反射成对象 /// </summary> /// <typeparam name="TService">接口类型</typeparam> /// <param name="overridedArguments">参数</param> /// <returns>具体类型</returns> public object Resolve(Type serviceType, object overridedArguments) { var overrides = Utils.GetParameterOverrides(overridedArguments); return(UnityContainerExtensions.Resolve(this, serviceType, overrides.ToArray())); }
/// <summary> /// 反射成对象 /// </summary> /// <typeparam name="TService">接口类型</typeparam> /// <param name="overridedArguments">参数</param> /// <returns>具体类型</returns> public TService Resolve <TService>(object overridedArguments) { var overrides = Utils.GetParameterOverrides(overridedArguments); return(UnityContainerExtensions.Resolve <TService>(this, overrides.ToArray())); }
/// <summary> /// 反射成对象 /// </summary> /// <typeparam name="TService">接口类型</typeparam> /// <returns>具体类型</returns> public object Resolve(Type type) { return(UnityContainerExtensions.Resolve(this, type)); }
/// <summary> /// 反射成对象 /// </summary> /// <typeparam name="TService">接口类型</typeparam> /// <returns>具体类型</returns> public TService Resolve <TService>() { return(UnityContainerExtensions.Resolve <TService>(this)); }
public T Resolve <T>() { return(UnityContainerExtensions.Resolve <T>(this)); }