public void CreateFromTypeWhenParentCanGenerateBothParametersWillReturnCorrectResult() { // Fixture setup var expectedParameterValues = new object[] { 1, 2m }; var parameterQueue = new Queue <object>(expectedParameterValues); var requestedType = typeof(DoubleParameterType <int, decimal>); var parameters = requestedType.GetConstructors().Single().GetParameters(); var container = new DelegatingSpecimenContext(); container.OnResolve = r => { if (parameters.Any(r.Equals)) { return(parameterQueue.Dequeue()); } return(null); }; var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system var result = sut.Create(requestedType, container); // Verify outcome var actual = (DoubleParameterType <int, decimal>)result; Assert.Equal(expectedParameterValues[0], actual.Parameter1); Assert.Equal(expectedParameterValues[1], actual.Parameter2); // Teardown }
/// <summary> /// 加载所有的Application.config文件 /// </summary> private static ConcurrentDictionary <int, ApplicationConfig> LoadConfigs() { var configs = new ConcurrentDictionary <int, ApplicationConfig>(); //获取Applications中所有的Application.Config string applicationsDirectory = WebUtility.GetPhysicalFilePath("~/Applications/"); foreach (var appPath in Directory.GetDirectories(applicationsDirectory)) { string fileName = Path.Combine(appPath, "Application.Config"); if (!File.Exists(fileName)) { continue; } string configType = string.Empty; XElement applicationElement = XElement.Load(fileName); //读取各个application节点中的属性 if (applicationElement != null) { configType = applicationElement.Attribute("configType").Value; Type applicationConfigClassType = Type.GetType(configType); if (applicationConfigClassType != null) { ConstructorInvoker applicationConfigConstructor = applicationConfigClassType.DelegateForCreateInstance(typeof(XElement)); ApplicationConfig app = applicationConfigConstructor(applicationElement) as ApplicationConfig; if (app != null) { configs[app.ApplicationId] = app; } } } } return(configs); }
private static void RunConstructorBenchmark() { ConstructorInfo ctorInfo = null; ConstructorInvoker invoker = null; var initMap = new Dictionary <string, Action> { { "Init info", () => { ctorInfo = typeof(Person).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null); } }, { "Init ctorInvoker", () => { invoker = typeof(Person).DelegateForCreateInstance(); } }, }; var actionMap = new Dictionary <string, Action> { { "Direct ctor", () => new Person() }, { "Reflection ctor", () => ctorInfo.Invoke(NoArgArray) }, { "Fasterflect ctor", () => typeof(Person).CreateInstance() }, { "Fasterflect cached ctor", () => invoker(NoArgArray) }, }; Execute("Benchmark for Object Construction", initMap, actionMap); }
/// <summary> /// Invokes the constructor <paramref name="ctorInfo"/> with <paramref name="parameters"/> as arguments. /// Leave <paramref name="parameters"/> empty if the constructor has no argument. /// </summary> public static object CreateInstance(this ConstructorInfo ctorInfo, params object[] parameters) { ConstructorInvoker ctor = ctorInfo.DelegateForCreateInstance(); object value = ctor(parameters); return(value); }
/// <summary> /// 初始化第三方帐号获取器 /// </summary> public static void InitializeAll() { if (!isInitialized) { lock (lockObject) { if (!isInitialized) { thirdAccountGetters = new ConcurrentDictionary <string, ThirdAccountGetter>(); foreach (var accountType in new AccountBindingService().GetAccountTypes()) { Type thirdAccountGetterClassType = Type.GetType(accountType.ThirdAccountGetterClassType); if (thirdAccountGetterClassType != null) { ConstructorInvoker thirdAccountGetterConstructor = thirdAccountGetterClassType.DelegateForCreateInstance(); ThirdAccountGetter thirdAccountGetter = thirdAccountGetterConstructor() as ThirdAccountGetter; if (thirdAccountGetter != null) { thirdAccountGetters[accountType.AccountTypeKey] = thirdAccountGetter; } } } isInitialized = true; } } } }
/// <summary> /// Create a new object for the type linked to the given key /// </summary> /// <param name="key">The value of Key type</param> /// <returns>The instance of type</returns> public static TBaseType CreateInstance(TKey key) { ConstructorInvoker invoke = null; delegates.TryGetValue(key, out invoke); return(invoke != null?invoke() : null); }
public void EmitConstructorInvokerInvokeWithParametersComplexTypes() { Type personType = typeof(Person); Type[] parameterTypes = { typeof(string), typeof(string), typeof(int), typeof(Child) }; ConstructorInvoker constructorInvoker = DynamicMethodHelper.EmitConstructorInvoker( personType, personType.GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null), parameterTypes); const string name = "javier"; const string surname = "sotomayor"; const int age = 45; const string childName = "child"; Child child = new Child(childName); Person person = (Person)constructorInvoker(name, surname, age, child); Assert.IsNotNull(person); Assert.AreEqual(name, person.Name); Assert.AreEqual(surname, person.Surname); Assert.AreEqual(age, person.Age); Assert.IsNotNull(person.Child); Assert.AreSame(child, person.Child); Assert.AreEqual(childName, person.Child.Name); }
public void CreateFromTypeWillInvokeContainerCorrectly() { // Fixture setup var requestedType = typeof(DoubleParameterType <long, short>); var parameters = requestedType.GetConstructors().Single().GetParameters(); var mockVerified = false; var contextMock = new DelegatingSpecimenContext(); contextMock.OnResolve = r => { if (parameters.Any(r.Equals)) { mockVerified = true; var pType = ((ParameterInfo)r).ParameterType; if (typeof(long) == pType) { return(new long()); } if (typeof(short) == pType) { return(new short()); } } throw new ArgumentException("Unexpected container request.", "r"); }; var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system sut.Create(requestedType, contextMock); // Verify outcome Assert.True(mockVerified, "Mock verification"); // Teardown }
public object Invoke(object[] args) { if (_invoker == null) { _invoker = ConstructorInfo.Invoker(); } return(_invoker(args)); }
/// <summary> /// Adds a new type to the internal dictionary /// </summary> /// <param name="key">The value of Key type </param> /// <param name="type">The type</param> public static void Add(TKey key, Type type) { if (type == null) { throw new ArgumentNullException("type"); } // Check if object is not a class if (type.IsClass == false) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "{0} is not a reference type.", type.FullName), "type"); } // Check if object is abstract if (type.IsAbstract == true) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "{0} is an abstract class, which can not be created.", type.FullName), "type"); } // Extra check if delegate not already added. if (delegates.ContainsKey(key) == false) { try { // Create the delegate for the type ConstructorInvoker invoke = CreateInvoker(type); // Try to invoke function (extra error check, // so the delegate is not added on error) invoke(); // The invoker executed correctly (no exceptions) // so let's add it to the dictionary delegates.Add(key, invoke); } catch (InvalidCastException) { throw new InvalidCastException( string.Format( CultureInfo.InvariantCulture, "{0} couldn't be casted to {1}.", type.FullName, typeof(TBaseType).FullName)); } } }
public void SutIsSpecimenBuilder() { // Fixture setup // Exercise system var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Verify outcome Assert.IsAssignableFrom <ISpecimenBuilder>(sut); // Teardown }
public void CreateWithNullContainerWillThrow() { // Fixture setup var sut = new ConstructorInvoker(new ModestConstructorQuery()); var dummyRequest = new object(); // Exercise system and verify outcome Assert.Throws <ArgumentNullException>(() => sut.Create(dummyRequest, null)); // Teardown }
public static void Main() { ConstructorInvoker ctor = Reflect.Constructor(typeof(long)); MemberGetter getValue = Reflect.Getter(typeof(long), "m_value"); MemberSetter setValue = Reflect.Setter(typeof(long), "m_value"); long integer = (long)ctor(); ValueTypeHolder holder = new ValueTypeHolder(integer); // IMPORTANT! setValue(holder, 8L); Console.WriteLine(getValue(holder)); Console.ReadLine(); }
public void QueryIsCorrect() { // Fixture setup var expectedPicker = new DelegatingConstructorQuery(); var sut = new ConstructorInvoker(expectedPicker); // Exercise system IConstructorQuery result = sut.Query; // Verify outcome Assert.Equal(expectedPicker, result); // Teardown }
public void CreateWithNullRequestWillReturnNull() { // Fixture setup var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system var dummyContainer = new DelegatingSpecimenContext(); var result = sut.Create(null, dummyContainer); // Verify outcome var expectedResult = new NoSpecimen(); Assert.Equal(expectedResult, result); // Teardown }
/// <summary> /// Create a new empty instance of the same type of OperationHost as this one /// </summary> /// <returns></returns> public OperationHost <TOp> CreateNew() { if (_ctorDlg == null) { _ctorDlg = GetType().DelegateForCreateInstance(); } var res = _ctorDlg.Invoke(); if (res is OperationHost <TOp> ophost) { return(ophost); } return(null); }
public void CreateFromTypeWithNoPublicConstructorWhenContainerCanSatisfyRequestReturnsCorrectResult() { // Fixture setup var container = new DelegatingSpecimenContext { OnResolve = r => new object() }; var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system var result = sut.Create(typeof(AbstractType), container); // Verify outcome var expectedResult = new NoSpecimen(typeof(AbstractType)); Assert.Equal(expectedResult, result); // Teardown }
public void TestConstructorWithArgs() { // Arrange var constructorInfo = typeof(Bar).GetConstructor(new[] { typeof(decimal), typeof(string) }); decimal arg1 = 1.11m; string arg2 = "123"; // Act var invoker = new ConstructorInvoker(constructorInfo); var obj = invoker.Invoke(arg1, arg2) as Bar; // Assert Assert.Equal(arg1, obj.DecimalProp); Assert.Equal(arg2, obj.StringProp); }
public void CreateFromTypeRequestWhenContainerCannotSatisfyParameterRequestWillReturnCorrectResult() { // Fixture setup var type = typeof(string); var container = new DelegatingSpecimenContext { OnResolve = r => new NoSpecimen(type) }; var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system var result = sut.Create(type, container); // Verify outcome var expectedResult = new NoSpecimen(type); Assert.Equal(expectedResult, result); // Teardown }
public void CreateFromTypeWhenParentCanGenerateOneParameterButNotTheOtherWillReturnCorrectNull() { // Fixture setup var requestedType = typeof(DoubleParameterType <string, int>); var parameters = requestedType.GetConstructors().Single().GetParameters(); var container = new DelegatingSpecimenContext { OnResolve = r => parameters[0] == r ? new object() : new NoSpecimen(r) }; var sut = new ConstructorInvoker(new ModestConstructorQuery()); // Exercise system var result = sut.Create(requestedType, container); // Verify outcome Assert.IsAssignableFrom <NoSpecimen>(result); // Teardown }
public void CreateReturnsCorrectResultWhenQueryReturnsEmptyConstructors() { // Fixture setup var dummyRequest = typeof(object); var query = new DelegatingConstructorQuery { OnSelectConstructors = t => Enumerable.Empty <IMethod>() }; var sut = new ConstructorInvoker(query); // Exercise system var dummyContext = new DelegatingSpecimenContext(); var result = sut.Create(dummyRequest, dummyContext); // Verify outcome var expectedResult = new NoSpecimen(dummyRequest); Assert.Equal(expectedResult, result); // Teardown }
/// <summary> /// Initializes a new instance of the <see cref="AttributeFactory" /> class. /// </summary> /// <param name="data">The data.</param> public AttributeFactory(CustomAttributeData data) { Data = data; var ctorInvoker = new ConstructorInvoker(data.Constructor); var ctorArgs = data.ConstructorArguments.Select(a => a.Value).ToArray(); m_attributeCreator = () => ctorInvoker.Invoke(ctorArgs); m_propertySetters = new List <Action <object> >(); foreach (var arg in data.NamedArguments) { var property = (PropertyInfo)arg.MemberInfo; var propertyAccessor = new PropertyAccessor(property); var value = arg.TypedValue.Value; m_propertySetters.Add(o => propertyAccessor.SetValue(o, value)); } }
public static void Main() { ConstructorInvoker ctor = Reflect.Constructor(typeof(Person), typeof(string), typeof(int)); MemberGetter getName = Reflect.Getter(typeof(Person), "Name"); MemberGetter getAge = Reflect.FieldGetter(typeof(Person), "Age"); MemberSetter setAge = Reflect.Setter(typeof(Person), "Age"); MultiSetter setBoth = Reflect.MultiSetter(typeof(Person), "Age", "Name"); Person person = (Person)ctor("John Doe", 21); setAge(person, 30); Console.WriteLine(getName(person)); Console.WriteLine(getAge(person)); setBoth(person, 35, "John Wick"); Console.WriteLine(getName(person)); Console.WriteLine(getAge(person)); Console.ReadLine(); }
internal static ConstructorInvoker Constructor(Type type, BindingFlags bindingFlags, ConstructorInfo ctor, Type[] parameterTypes) { bindingFlags &= FasterflectFlags.InstanceAnyDeclaredOnly; CtorInfo info = new CtorInfo(type, bindingFlags, parameterTypes); ConstructorInvoker value = Constructors.Get(info); if (value != null) { return(value); } if (ctor == null && (!type.IsValueType || parameterTypes.Length != 0)) { ctor = ReflectLookup.Constructor(type, bindingFlags, parameterTypes) ?? throw new MissingMemberException(type.FullName, "ctor()"); } value = (ConstructorInvoker) new CtorInvocationEmitter(type, ctor).GetDelegate(); Constructors.Insert(info, value); return(value); }
private static void ExecuteCacheApi(Type type) { List <int> range = Enumerable.Range(0, 10).ToList(); // Let's cache the getter for the static InstanceCount MemberGetter count = type.DelegateForGetFieldValue("InstanceCount"); // Now cache the 2-arg constructor of Person and playaround with the delegate returned var currentInstanceCount = (int)count(null); ConstructorInvoker ctor = type.DelegateForCreateInstance(new[] { typeof(int), typeof(string) }); range.ForEach(i => { object obj = ctor(i, "_" + i); AssertTrue(++currentInstanceCount == (int)count(null)); AssertTrue(i == (int)obj.GetFieldValue("id")); AssertTrue("_" + i == obj.GetPropertyValue("Name").ToString()); }); // Getter/setter MemberSetter nameSetter = type.DelegateForSetPropertyValue("Name"); MemberGetter nameGetter = type.DelegateForGetPropertyValue("Name"); object person = ctor(1, "John"); AssertTrue("John" == (string)nameGetter(person)); nameSetter(person, "Jane"); AssertTrue("Jane" == (string)nameGetter(person)); // Invoke method person = type.CreateInstance(); MethodInvoker walk = type.DelegateForCallMethod("Walk", new[] { typeof(int) }); range.ForEach(i => walk(person, i)); AssertTrue(range.Sum() == (int)person.GetFieldValue("milesTraveled")); // Map properties var ano = new { Id = 4, Name = "Doe" }; ObjectMapper mapper = ano.GetType().DelegateForMap(type); mapper(ano, person); AssertTrue(4 == (int)person.GetPropertyValue("Id")); AssertTrue("Doe" == (string)person.GetPropertyValue("Name")); }
public void CreateFromTypeWillUseFirstConstructorItCanSatisfy() { // Fixture setup var requestedType = typeof(MultiUnorderedConstructorType); var ctor1 = requestedType.GetConstructor(new[] { typeof(MultiUnorderedConstructorType.ParameterObject) }); var ctor2 = requestedType.GetConstructor(new[] { typeof(string), typeof(int) }); var picker = new DelegatingConstructorQuery { OnSelectConstructors = t => new IMethod[] { new ConstructorMethod(ctor1), new ConstructorMethod(ctor2) } }; var sut = new ConstructorInvoker(picker); var ctor2Params = ctor2.GetParameters(); var expectedText = "Anonymous text"; var expectedNumber = 14; var context = new DelegatingSpecimenContext(); context.OnResolve = r => { if (ctor2Params.Any(r.Equals)) { var pType = ((ParameterInfo)r).ParameterType; if (typeof(string) == pType) { return(expectedText); } if (typeof(int) == pType) { return(expectedNumber); } } return(new NoSpecimen(r)); }; // Exercise system var result = sut.Create(requestedType, context); // Verify outcome var actual = Assert.IsAssignableFrom <MultiUnorderedConstructorType>(result); Assert.Equal(expectedText, actual.Text); Assert.Equal(expectedNumber, actual.Number); // Teardown }
public static void Main() { ConstructorInvoker ctor = Reflect.Constructor(typeof(Animal), typeof(string), typeof(int)); MemberGetter getName = Reflect.Getter(typeof(Animal), "Name"); MemberGetter getAge = Reflect.FieldGetter(typeof(Animal), "Age"); MemberSetter setAge = Reflect.Setter(typeof(Animal), "Age"); MultiSetter setBoth = Reflect.MultiSetter(typeof(Animal), "Age", "Name"); Animal animal = (Animal)ctor("Charlie", 5); ValueTypeHolder holder = new ValueTypeHolder(animal); // IMPORTANT! setAge(holder, 8); Console.WriteLine(getName(holder)); Console.WriteLine(getAge(holder)); setBoth(holder, 10, "Buster"); Console.WriteLine(getName(holder)); Console.WriteLine(getAge(holder)); Console.ReadLine(); }
/// <summary> /// 加载所有的Application.config文件 /// </summary> private static ConcurrentDictionary <int, MobileClientApplicationConfig> LoadConfigs() { var configs = new ConcurrentDictionary <int, MobileClientApplicationConfig>(); //获取Applications中所有的Application.Config string mobileClientDirectory = WebUtility.GetPhysicalFilePath("~/MobileClient/"); if (!Directory.Exists(mobileClientDirectory)) { return(configs); } int i = 10000; foreach (var mobilePath in Directory.GetDirectories(mobileClientDirectory)) { string fileName = Path.Combine(mobilePath, "Application.Config"); if (!File.Exists(fileName)) { continue; } string configType = string.Empty; XElement mobileElement = XElement.Load(fileName); //读取各个application节点中的属性 if (mobileElement != null) { configType = mobileElement.Attribute("configType").Value; Type mobileClassType = Type.GetType(configType); if (mobileClassType != null) { ConstructorInvoker mobileConfigConstructor = mobileClassType.DelegateForCreateInstance(typeof(XElement)); MobileClientApplicationConfig app = mobileConfigConstructor(mobileElement) as MobileClientApplicationConfig; if (app != null) { configs[i] = app; i++; } } } } return(configs); }
/// <summary> /// 获取Application集合 /// </summary> /// <param name="onlyIsEnabled">仅启用的应用</param> /// <returns>返回满足条件的应用集合</returns> public IEnumerable <ApplicationBase> GetAll(bool?onlyIsEnabled = null) { string cacheKey = GetCacheKey_AllApplicationBases(); ICacheService cacheService = DIContainer.Resolve <ICacheService>(); List <ApplicationBase> allApplications = cacheService.Get <List <ApplicationBase> >(cacheKey); if (allApplications == null) { IEnumerable <ApplicationModel> applicationModels = applicationRepository.GetAll("DisplayOrder"); List <ApplicationBase> apps = new List <ApplicationBase>(); foreach (var model in applicationModels) { ApplicationConfig config = getConfig(model.ApplicationId); if (config == null) { continue; } Type applicationClassType = config.ApplicationType; if (applicationClassType == null) { continue; } //使用Fasterflect提升反射效率 ConstructorInvoker applicationConstructor = applicationClassType.DelegateForCreateInstance(typeof(ApplicationModel)); ApplicationBase app = applicationConstructor(model) as ApplicationBase; if (app != null) { apps.Add(app); } } allApplications = apps; cacheService.Add(cacheKey, allApplications, CachingExpirationType.Stable); } if (onlyIsEnabled.HasValue) { return(allApplications.Where(a => a.IsEnabled == true)); } return(allApplications); }
public void EmitConstructorInvokerInvokeParameterlessConstructor() { Type personType = typeof(Person); Type[] parameterTypes = { }; ConstructorInvoker constructorInvoker = DynamicMethodHelper.EmitConstructorInvoker( personType, personType.GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null), parameterTypes); Person person = (Person)constructorInvoker(); Assert.IsNotNull(person); Assert.AreEqual(Person.DEFAULT_NAME, person.Name); Assert.AreEqual(Person.DEFAULT_SURNAME, person.Surname); Assert.AreEqual(Person.DEFAULT_AGE, person.Age); }
public AttributeFactory(CustomAttributeData data) { this.Data = data; var ctorInvoker = new ConstructorInvoker(data.Constructor); var ctorArgs = data.ConstructorArguments.Select(a => a.Value).ToArray(); this.m_attributeCreator = () => ctorInvoker.Invoke(ctorArgs); this.m_propertySetters = new List<Action<object>>(); foreach (var arg in data.NamedArguments) { var property = (PropertyInfo)arg.MemberInfo; var propertyAccessor = new PropertyAccessor(property); var value = arg.TypedValue.Value; this.m_propertySetters.Add(o => propertyAccessor.SetValue(o, value)); } }
internal override void InitializeInvoker() { invoker = type.DelegateForCreateInstance(GetParamTypes()); }
public void ConstructorInvokerConstructorTest() { Type myType = typeof(MyClass); ConstructorInfo constructorInfo = myType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, Type.EmptyTypes, null); ConstructorInvoker target = new ConstructorInvoker(constructorInfo); Assert.IsNotNull(target); }