private static ICouchbaseClientFactory GetFactoryInstance(string typeName, Func <ICouchbaseClientFactory> createDefault) { if (String.IsNullOrEmpty(typeName)) { return(createDefault()); } var type = Type.GetType(typeName, false); if (type == null) { throw new System.Configuration.ConfigurationErrorsException("Could not load type: " + typeName); } if (!typeof(ICouchbaseClientFactory).IsAssignableFrom(type)) { throw new System.Configuration.ConfigurationErrorsException("Type '" + typeName + "' must implement IMemcachedClientFactory"); } return(FastActivator.Create(type) as ICouchbaseClientFactory); }
/// <summary> /// Deserializes an object. /// </summary> /// <param name="archive">Archive containing the serialized object.</param> /// <returns>The deserialized object.</returns> /// <exception cref="VersionNotSupportedException">Serializer version is not supported.</exception> public override IDictionary <TKey, TValue> Deserialize(DeserializationArchive archive) { if (archive.Version == 1) { // read number of dictionary entries int count = archive.ReadInt32(); // read elements from the archive and put them into the dictionary var dictionary = (IDictionary <TKey, TValue>)FastActivator.CreateInstance(archive.DataType); for (int i = 0; i < count; i++) { var key = (TKey)archive.ReadObject(archive.Context); var value = (TValue)archive.ReadObject(archive.Context); dictionary.Add(key, value); } return(dictionary); } throw new VersionNotSupportedException(archive); }
public void Should_be_able_to_suck_out_an_interface() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize <Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { Type proxyType = InterfaceImplementationBuilder.GetProxyFor(typeof(MessageA)); var message = (MessageA)FastActivator.Create(proxyType); _serializer.Populate(jsonReader, message); message.Name.ShouldEqual("Joe"); } }
private static void ConfigureService <TService, TRegistry>(IServiceConfigurator <TService> service, Action <TService> start, Action <TService> stop) where TRegistry : Registry { var container = new Container(x => { x.For <IConfiguration>() .Singleton() .Add <Configuration>(); x.For <TService>() .Singleton() .Use <TService>(); }); TRegistry registry = FastActivator <TRegistry> .Create(container); container.Configure(x => x.AddRegistry(registry)); service.HowToBuildService(builder => container.GetInstance <TService>()); service.WhenStarted(start); service.WhenStopped(stop); }
public static void Initialize(string fileName, string env = null) { if (!string.IsNullOrWhiteSpace(env)) { env = Environment.GetEnvironmentVariable(env); } s_path = env ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); if (!File.Exists(s_path)) { Instance = FastActivator <T> .Create(); Save(); } var str = File.ReadAllText(s_path); str = Hjson.HjsonValue.Parse(str).ToString(Hjson.Stringify.Plain); Json = JObject.Parse(str); Instance = Json.ToObject <T>(); }
/// <summary> /// Creates the provider by using the factory (if present) or directly instantiating by type name /// </summary> /// <returns></returns> public TFactory CreateInstance() { //check if we have a factory if (this.instance == null) { var type = this.Factory; if (type == null) { if (this.IsOptional || !this.ElementInformation.IsPresent) { return(null); } throw new ConfigurationErrorsException("factory must be defined"); } this.instance = (TFactory)FastActivator.Create(type); this.instance.Initialize(this.Parameters); } return(this.instance); }
internal static void ProxyJoins(object entity) { ClassDefineMetadata metadata = RepositoryFramework.GetDefineMetadataAndCheck(entity.GetType()); var joins = metadata.ClassJoinDefines.Values.Cast <ClassJoinDefineMetadata>().Where(o => o.JoinType == MethodJoinType.PropertyGet); var ta = TypeAccessor.GetAccessor(metadata.EntityType); foreach (var join in joins) { var value = ta.GetProperty(join.JoinName, entity); //已经为代理对象,直接忽略 if (IsProxy(value)) { ((IProxy)value).Reset(); continue; } var type = join.Method.ReturnType; if (EntityUtil.IsGenericList(type)) { var itemType = type.GetGenericArguments()[0]; var proxyType = typeof(ProxyCollection <>).MakeGenericType(itemType); IProxyCollection proxy = (IProxyCollection)FastActivator.Create(proxyType); proxy.Init(entity, join); ta.SetProperty(join.JoinName, entity, proxy); } else { var ei = new EntityProxyInterceptor(entity, join); var proxy = ProxyProvider.GetCreateFunc(type)(new IInterceptor[] { ei }); ei.IsConstructed = true; ta.SetProperty(join.JoinName, entity, proxy); } } }
public object Resolve([NotNull] Type type) { Guard.NotNull(type, nameof(type)); var typeInfo = type.GetTypeInfo(); object result; Exception innerException = null; if (typeInfo.IsInterface || typeInfo.IsAbstract) { result = null; } else { try { result = FastActivator.CreateInstance(type); } catch (Exception ex) { innerException = ex; result = null; } } if (result == null) { throw new InvalidOperationException(string.Format( Properties.Resources.UnableToResolveTypeWithDependencyResolver, type.FullName, typeof(RepositoryDependencyResolver).Name), innerException); } return(result); }
public void Save(Type projectionType, IEvent @event, EventOrigin eventOrigin) { if (ReferenceEquals(null, projectionType)) { throw new ArgumentNullException(nameof(projectionType)); } if (ReferenceEquals(null, @event)) { throw new ArgumentNullException(nameof(@event)); } if (ReferenceEquals(null, eventOrigin)) { throw new ArgumentNullException(nameof(eventOrigin)); } string contractId = projectionType.GetContractId(); var instance = FastActivator.CreateInstance(projectionType); var statefullProjection = instance as IProjectionDefinition; if (statefullProjection != null) { var projectionIds = statefullProjection.GetProjectionIds(@event); foreach (var version in GetProjectionVersions(contractId)) { foreach (var projectionId in projectionIds) { ISnapshot snapshot = snapshotStore.Load(contractId, projectionId, version); ProjectionStream projectionStream = LoadProjectionStream(projectionType, version, projectionId, snapshot); int snapshotMarker = snapshotStrategy.GetSnapshotMarker(projectionStream.Commits, snapshot.Revision); var commit = new ProjectionCommit(projectionId, version, @event, snapshotMarker, eventOrigin, DateTime.UtcNow); projectionStore.Save(commit); } } } }
public PiecewiseZeroInflationCurve(Date referenceDate, Calendar calendar, DayCounter dayCounter, Period lag, Frequency frequency, bool indexIsInterpolated, double baseZeroRate, Handle <YieldTermStructure> nominalTS, List <BootstrapHelper <ZeroInflationTermStructure> > instruments, double accuracy = 1.0e-12, Interpolator i = default(Interpolator), Bootstrap bootstrap = default(Bootstrap)) : base(referenceDate, calendar, dayCounter, baseZeroRate, lag, frequency, indexIsInterpolated, nominalTS) { _instruments_ = instruments; accuracy_ = accuracy; if (bootstrap == null) { bootstrap_ = FastActivator <Bootstrap> .Create(); } else { bootstrap_ = bootstrap; } if (i == null) { interpolator_ = FastActivator <Interpolator> .Create(); } else { interpolator_ = i; } _traits_ = FastActivator <Traits> .Create(); bootstrap_.setup(this); }
private T StringToInstance(string text) { if (text[0] != MapStart) { string message = string.Format("Types should start with a '{0}', expecting serialized type '{1}', got string starting with: {2}", MapStart, typeof(T).Name, text.Substring(0, text.Length < 50 ? text.Length : 50)); throw new SerializationException(message); } T instance = FastActivator <T> .Create(); try { ReadMap(text, (key, value) => _properties.WithValue(key, serializer => serializer.Read(instance, value))); } catch (Exception ex) { throw TypeSerializerException.New(this, text, ex); } return(instance); }
SelectiveConsumer <T> CreateFilteredConsumer <T>(SelectiveConsumer <T> consumer) { if (!typeof(T).Implements(typeof(Response <>))) { return(consumer); } var types = new[] { typeof(TRequest), typeof(T), typeof(T).GetDeclaredGenericArguments().Single() }; var args = new object[] { RequestId }; var responseFilter = (ResponseFilter <T>)FastActivator.Create(typeof(RequestIdFilter <,>), types, args); SelectiveConsumer <T> result = candidate => { if (!responseFilter.Accept(candidate)) { return(null); } return(consumer(candidate)); }; return(result); }
private static void LoadBuiltInDeserializers() { Assembly.GetExecutingAssembly() .GetTypes() .Where(x => !x.IsGenericType) .Where(x => x.Namespace == typeof(StringDeserializer).Namespace) .Each(type => { type.GetInterfaces() .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IObjectDeserializer <>)) .Each(interfaceType => { Type itemType = interfaceType.GetGenericArguments().First(); _log.DebugFormat("Adding deserializer for {0} ({1})", itemType.Name, type.Name); var deserializer = FastActivator.Create(type) as IObjectDeserializer; _deserializers.Add(itemType.AssemblyQualifiedName, deserializer); _deserializersByType.Add(itemType, deserializer); }); }); }
public static void ShowWindow <T, TParam>(TParam param) where T : Window { Debug.WriteLine("Show Window : {0}", typeof(T)); if (Windows.ContainsKey(typeof(T))) { CloseWindow <T>(); } var newThread = new Thread( () => { SynchronizationContext.SetSynchronizationContext( new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher)); var window = FastActivator <TParam> .CreateInstance <T>(param); if (window != null) { Windows.TryAdd(typeof(T), window); window.Closed += (s, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background); window.Show(); } Dispatcher.Run(); }); newThread.SetApartmentState(ApartmentState.STA); newThread.IsBackground = true; newThread.Start(); }
/// <summary> /// Creates the provider by using the factory (if present) or directly instantiating by type name /// </summary> /// <returns></returns> public T CreateInstance() { //check if we have a factory if (this.factoryInstance == null) { var type = this.Factory; if (type != null) { try { var instance = (IProviderFactory <T>)FastActivator.Create(type); instance.Initialize(this.parameters); this.factoryInstance = instance; } catch (Exception e) { throw new InvalidOperationException(String.Format("Could not initialize the provider factory {0}. Check the InnerException for details.", type), e); } } } // no factory, use the provider type if (this.factoryInstance == null) { var type = this.Type; if (type == null) { return(null); } return((T)FastActivator.Create(type)); } return(factoryInstance.Create()); }
static EntityFactory() { var typesWithFactory = new List <Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { typesWithFactory.AddRange( assembly.GetTypes() .Where(type => type.GetCustomAttributes(typeof(EntityFactoryAttribute), true).Any())); } catch (ReflectionTypeLoadException) { } } foreach (var type in typesWithFactory) { var factoryAttribute = type.GetCustomAttributes(typeof(EntityFactoryAttribute), true).SingleOrDefault() as EntityFactoryAttribute; if (factoryAttribute == null) { continue; } var factory = FastActivator.CreateInstance(factoryAttribute.FactoryType) as IFactory; if (factory != null) { RegisterFactory(type, factory); } } }
public void Save(Type projectionType, CronusMessage cronusMessage) { if (ReferenceEquals(null, projectionType)) { throw new ArgumentNullException(nameof(projectionType)); } if (ReferenceEquals(null, cronusMessage)) { throw new ArgumentNullException(nameof(cronusMessage)); } var projection = FastActivator.CreateInstance(projectionType) as IProjectionDefinition; if (projection != null) { var projectionIds = projection.GetProjectionIds(cronusMessage.Payload as IEvent); string contractId = projectionType.GetContractId(); foreach (var projectionId in projectionIds) { foreach (var version in GetProjectionVersions(contractId)) { ISnapshot snapshot = snapshotStore.Load(contractId, projectionId, version); ProjectionStream projectionStream = LoadProjectionStream(projectionType, version, projectionId, snapshot); int snapshotMarker = snapshotStrategy.GetSnapshotMarker(projectionStream.Commits, snapshot.Revision); EventOrigin eventOrigin = cronusMessage.GetEventOrigin(); DateTime timestamp = DateTime.UtcNow; IEvent @event = cronusMessage.Payload as IEvent; var commit = new ProjectionCommit(projectionId, version, @event, snapshotMarker, eventOrigin, timestamp); projectionStore.Save(commit); } } } }
public object ResolveUnregistered(Type type, ILifetimeScope scope = null) { FastActivator activator; object[] parameterInstances = null; if (!_cachedActivators.TryGetValue(type, out activator)) { var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var constructor in constructors) { var parameterTypes = constructor.GetParameters().Select(p => p.ParameterType).ToArray(); if (TryResolveAll(parameterTypes, out parameterInstances, scope)) { activator = new FastActivator(constructor); _cachedActivators.TryAdd(type, activator); break; } } } if (activator != null) { if (parameterInstances == null) { TryResolveAll(activator.ParameterTypes, out parameterInstances, scope); } if (parameterInstances != null) { return(activator.Activate(parameterInstances)); } } throw new SmartException("No constructor for {0} was found that had all the dependencies satisfied.".FormatInvariant(type.Name.NaIfEmpty())); }
public object ResolveUnregistered(Type type, ILifetimeScope scope = null) { FastActivator activator; object[] parameterInstances = null; if (!_cachedActivators.TryGetValue(type, out activator)) { var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var constructor in constructors) { var parameterTypes = constructor.GetParameters().Select(p => p.ParameterType).ToArray(); if (TryResolveAll(parameterTypes, out parameterInstances, scope)) { activator = new FastActivator(constructor); _cachedActivators.TryAdd(type, activator); break; } } } if (activator != null) { if (parameterInstances == null) { TryResolveAll(activator.ParameterTypes, out parameterInstances, scope); } if (parameterInstances != null) { return(activator.Activate(parameterInstances)); } } throw new Exception(); }
public TSaga CreateInstance(IConsumeContext <TMessage> context, Guid sagaId) { return(FastActivator <TSaga> .Create(sagaId)); }
void check <S>(string name) where S : IGeneralStatistics, new () { S s = FastActivator <S> .Create(); for (int i = 0; i < data.Length; i++) { s.add(data[i], weights[i]); } double calculated, expected; double tolerance; if (s.samples() != data.Length) { QAssert.Fail(name + ": wrong number of samples\n" + " calculated: " + s.samples() + "\n" + " expected: " + data.Length); } expected = weights.Sum(); calculated = s.weightSum(); if (calculated != expected) { QAssert.Fail(name + ": wrong sum of weights\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = data.Min(); calculated = s.min(); if (calculated != expected) { QAssert.Fail(name + ": wrong minimum value\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = data.Max(); calculated = s.max(); if (calculated != expected) { QAssert.Fail(name + ": wrong maximum value\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = 4.3; tolerance = 1.0e-9; calculated = s.mean(); if (Math.Abs(calculated - expected) > tolerance) { QAssert.Fail(name + ": wrong mean value\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = 2.23333333333; calculated = s.variance(); if (Math.Abs(calculated - expected) > tolerance) { QAssert.Fail(name + ": wrong variance\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = 1.4944341181; calculated = s.standardDeviation(); if (Math.Abs(calculated - expected) > tolerance) { QAssert.Fail(name + ": wrong standard deviation\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = 0.359543071407; calculated = s.skewness(); if (Math.Abs(calculated - expected) > tolerance) { QAssert.Fail(name + ": wrong skewness\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } expected = -0.151799637209; calculated = s.kurtosis(); if (Math.Abs(calculated - expected) > tolerance) { QAssert.Fail(name + ": wrong kurtosis\n" + " calculated: " + calculated + "\n" + " expected: " + expected); } }
void CacheMessageTypesForSaga() { TSaga saga = FastActivator <TSaga> .Create(CombGuid.Generate()); saga.EnumerateDataEvents(type => _messageTypes.Add(type)); }
public PiecewiseDefaultCurve(int settlementDays, Calendar calendar, List <CdsHelper> instruments, DayCounter dayCounter, List <Handle <Quote> > jumps, List <Date> jumpDates, double accuracy) : this(settlementDays, calendar, instruments, dayCounter, jumps, jumpDates, accuracy, FastActivator <Interpolator> .Create(), FastActivator <BootStrap> .Create()) { }
public PiecewiseDefaultCurve(Date referenceDate, List <CdsHelper> instruments, DayCounter dayCounter, List <Handle <Quote> > jumps, List <Date> jumpDates, double accuracy, Interpolator i) : this(referenceDate, instruments, dayCounter, jumps, jumpDates, accuracy, i, FastActivator <BootStrap> .Create()) { }
/// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> public static object CreateInstance(this Type type, params object[] args) { return(FastActivator.Create(type, args)); }
/// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <param name="configurator"></param> /// <param name="serializerType"></param> /// <returns></returns> public static T SetDefaultSerializer <T>(this T configurator, Type serializerType) where T : EndpointFactoryConfigurator { return(SetDefaultSerializer(configurator, () => (IMessageSerializer)FastActivator.Create(serializerType))); }
public IEnumerable <IDiscoveryResult <object> > Scan(DiscoveryContext context) { List <Type> allTypes = context.Assemblies .SelectMany(asm => asm .GetLoadableTypes() .Where(type => type.IsAbstract == false && type.IsClass && typeof(IDiscovery <object>).IsAssignableFrom(type))) .ToList(); IEnumerable <IDiscovery <object> > discoveries = allTypes .Where(candidate => allTypes.Where(t => t.BaseType == candidate).Any() == false) // filter out discoveries which inherit from each other. We remove the base discoveries .Select(dt => (IDiscovery <object>)FastActivator.CreateInstance(dt)); foreach (var discovery in discoveries) { logger.Info(() => $"Discovered {discovery.Name}"); yield return(discovery.Discover(context)); } }
public CachedWorker(IWorkerInfo worker) { Worker = worker; MessageWorkers = new GenericTypeCache <IWorkerInfo>(typeof(IWorkerInfo <>), type => (IWorkerInfo)FastActivator.Create(typeof(WorkerInfo <>), new Type[] { type })); }
private T GetInstance <T>() { _called.Retrieve(typeof(T), () => true); return(FastActivator <T> .Create()); }
public PiecewiseDefaultCurve(Date referenceDate, List <CdsHelper> instruments, DayCounter dayCounter) : this(referenceDate, instruments, dayCounter, new List <Handle <Quote> >(), new List <Date>(), 1.0e-12, FastActivator <Interpolator> .Create(), FastActivator <BootStrap> .Create()) { }