public override void Register(IServiceLocatorAdapter adapter, IServiceLocatorStore store, IRegistration registration, ResolutionPipeline pipeline) { var mappedFromType = registration.GetMappedFromType(); var mappedToType = registration.GetMappedToType(); if (mappedFromType != mappedToType) { adapter.RegisterFactoryMethod(mappedFromType, () => pipeline.Execute(mappedFromType)); RegisterLazy(adapter, mappedFromType, pipeline); adapter.Register(mappedToType, mappedToType); RegisterContextual(adapter, mappedToType); } else { var serviceLocator = adapter.GetInstance<IServiceLocator>(); adapter.RegisterFactoryMethod(mappedToType, () => { var instance = serviceLocator.GetInstance(mappedToType, "default." + mappedToType, new IResolutionArgument[0]); return instance; }); serviceLocator.Register(new NamedRegistration(mappedToType, mappedToType, "default." + mappedToType)); } RegisterLazy(adapter, mappedToType, pipeline); RegisterTypeResolver(adapter, mappedFromType); RegisterContextual(adapter, mappedFromType); }
public virtual void Unregister(IRegistration registration) { lock (_registrationListLock) { _registrationList.Remove(registration); } }
public void Add(IRegistration registration) { if (registration.Key == null) { // Default _defaultIndex.Add(registration.Type, registration); } else { // Keyed Dictionary<object, IRegistration> keyedEntry; if (_keyedIndex.TryGetValue(registration.Type, out keyedEntry)) { // Add to already existing entry keyedEntry.Add(registration.Key, registration); } else { // Add new keyed entry keyedEntry = new Dictionary<object, IRegistration>(); keyedEntry.Add(registration.Key, registration); _keyedIndex.Add(registration.Type, keyedEntry); } } }
protected RabbitListener createListener(IRegistration registration, Exchange exchange) { // create a channel var connection = _connFactory.ConnectTo(exchange); // create a listener RabbitListener listener = new RabbitListener(registration, exchange, connection); listener.OnEnvelopeReceived += dispatcher => { Log.Debug("Got an envelope from the RabbitListener: dispatching."); // the dispatcher encapsulates the logic of giving the envelope to handlers dispatcher.Dispatch(); }; listener.OnClose += _listeners.Remove; //TODO: Resolve that RabbitListener does not implement OnConnectionError //listener.OnConnectionError(new ReconnectOnConnectionErrorCallback(_channelFactory)); // store the listener _listeners.Add(registration, listener); // put it on another thread so as not to block this one // don't continue on this thread until we've started listening ManualResetEvent startEvent = new ManualResetEvent(false); Thread listenerThread = new Thread(listener.Start); listenerThread.Name = string.Format("{0} on {1}:{2}{3}", exchange.QueueName, exchange.HostName, exchange.Port, exchange.VirtualHost); listenerThread.Start(startEvent); return listener; }
public virtual void Register(IRegistration registration) { lock (_registrationListLock) { _registrationList.Add(registration); } }
public void Register(IRegistration registration) { _log.Debug("Enter Register"); // first, get the topology based on the registration info RoutingInfo routing = _topoSvc.GetRoutingInfo(registration.Info); // next, pull out all the consumer exchanges IEnumerable<Exchange> exchanges = from route in routing.Routes select route.ConsumerExchange; foreach (Exchange ex in exchanges) { IConnection conn = _connFactory.ConnectTo(ex); // create a listener RabbitListener listener = new RabbitListener(registration, ex, conn); listener.OnEnvelopeReceived += this.listener_OnEnvelopeReceived; listener.OnClose += _listeners.Remove; // put it on another thread so as not to block this one Thread listenerThread = new Thread(listener.Start); listenerThread.Name = string.Format("{0} on {1}:{2}{3}", ex.QueueName, ex.HostName, ex.Port, ex.VirtualHost); listenerThread.Start(); // store the listener _listeners.Add(registration, listener); } _log.Debug("Leave Register"); }
public override object GetInstance(IContainer container, IRegistration registration) { if (IsDisposed) throw new ObjectDisposedException("ThreadStaticContainerLifecycle"); var lifecycle = GetThreadStaticLifecycle(); return lifecycle.GetInstance(container, registration); }
public FuncNoKeyRegistration(IRegistration delegateRegistration) { this.delegateRegistration = delegateRegistration; this.funcType = Expression.GetFuncType(Type.GetTypeFromHandle(delegateRegistration.TypeHandle)).TypeHandle; var registrationContext = Expression.Parameter(typeof(IRegistrationContext), "registrationContext"); this.generator = Expression.Lambda<Func<IRegistrationContext, object>>(this.GetInstanceExpression(registrationContext), registrationContext).Compile(); }
public RabbitListener(IRegistration registration, Exchange exchange, IConnection connection) { _registration = registration; _exchange = exchange; _connection = connection; _log = LogManager.GetLogger(this.GetType()); }
/// <summary> /// Initializes a new instance of the <see cref="TeamProjects" /> class. /// </summary> /// <param name="tfsCollectionUri">The TFS collection URI.</param> /// <param name="tfsCredentials">The TFS credentials.</param> public TeamProjects(Uri tfsCollectionUri, ITfsCredentials tfsCredentials) { this._tfsCollectionUri = tfsCollectionUri; this._tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsCollectionUri, tfsCredentials); this._registration = (IRegistration)this._tfsTeamProjectCollection.GetService(typeof(IRegistration)); this._commonStructureService = this._tfsTeamProjectCollection.GetService<ICommonStructureService>(); }
public PropertyFacilityRegistration(IRegistration inner, FinalRegistrationOptions options) { if (inner == null) throw new ArgumentNullException("inner", "inner is null."); if (options == null) throw new ArgumentNullException("options", "options is null."); _options = options; _inner = inner; }
/// <summary> /// Removes the instance for the registration from the local storage cache. /// </summary> /// <param name="registration">The IRegistration returned when the type was registered in the IOC container.</param> public void InvalidateInstanceCache(IRegistration registration) { // nothing stored yet if (localStorage == null) return; localStorage.Remove(registration.Key); }
public override void Register(IServiceLocatorAdapter adapter, IServiceLocatorStore store, IRegistration registration, ResolutionPipeline pipeline) { var namedRegistration = (INamedRegistration)registration; var mappedTo = registration.GetMappedTo(); adapter.RegisterInstanceWithName(registration.GetMappedToType(), mappedTo, namedRegistration.Key); adapter.RegisterInstanceWithName(registration.GetMappedFromType(), mappedTo, namedRegistration.Key); }
public void Unregister(IRegistration registration) { RabbitListener listener; if (_listeners.TryGetValue(registration, out listener)) { try { listener.Stop(); } catch { } } }
public TeamProjectCollections(Uri tfsUri, ITfsCredentials tfsCredentials) { this._tfsUri = tfsUri; this._tfsCredentials = tfsCredentials; this._tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri, this._tfsCredentials); this._tfsConfigurationServer = this._tfsTeamProjectCollection.GetConfigurationServer(); this._registration = (IRegistration)this._tfsTeamProjectCollection.GetService(typeof(IRegistration)); this._teamProjectCollectionService = this._tfsConfigurationServer.GetService<ITeamProjectCollectionService>(); }
public void Register(IServiceLocatorAdapter adapter, IServiceLocatorStore store, IRegistration registration, ResolutionPipeline pipeline) { if (registration is ConstructorRegistration) { var constructorRegistration = registration as ConstructorRegistration; store.Get<IInjectionOverrideStore>().Add(constructorRegistration.Arguments); } }
public ConstructorInjectionCodeGenerator(TemplateRegistrationMetadata metadata, string assignToVariable, bool declareVariable, string indent) { _metadata = metadata; _registration = metadata.Registration; _assignToVariable = assignToVariable; _declareVariable = declareVariable; _indent = indent; _stringBuilder = new StringBuilder(2000); }
public RabbitEnvelopeDispatcher(IRegistration registration, Envelope envelope, IModel channel, ulong deliveryTag) { _registration = registration; _channel = channel; _deliveryTag = deliveryTag; this.Envelope = envelope; _log = LogManager.GetLogger(this.GetType()); }
private static string GetMessage(IRegistration registration) { var msg = "Registration for type: " + registration.ReturnType; if (registration.Key != null) msg += " with key: " + registration.Key; msg += " is invalid."; return msg; }
public void Initialize() { lock (this) { if (this.reg == null && this.trial == null) { this.reg = new Registration(); this.trial = new TrialCounter(); } } }
public override void Register(IServiceLocatorAdapter adapter, IServiceLocatorStore store, IRegistration registration, ResolutionPipeline pipeline) { var mappedFromType = registration.GetMappedFromType(); var mappedToType = registration.GetMappedToType(); adapter.RegisterFactoryMethod(mappedFromType, () => pipeline.Execute(mappedFromType)); adapter.RegisterInstance(mappedToType, registration.GetMappedTo()); RegisterLazy(adapter, mappedFromType, pipeline); RegisterLazy(adapter, mappedToType, pipeline); RegisterContextual(adapter, mappedFromType); RegisterContextual(adapter, mappedToType); }
public override void Register(IServiceLocatorAdapter adapter, IServiceLocatorStore store, IRegistration registration, ResolutionPipeline pipeline) { var namedRegistration = (INamedRegistration) registration; var mappedToType = registration.GetMappedToType(); var mappedFromType = registration.GetMappedFromType(); adapter.RegisterWithName(mappedToType, mappedToType, namedRegistration.Key); adapter.RegisterWithName(mappedFromType, mappedToType, namedRegistration.Key); RegisterNamedLazy(adapter, mappedFromType, namedRegistration.Key); RegisterNamedLazy(adapter, mappedToType, namedRegistration.Key); }
public override object GetInstance(IContainer container, IRegistration registration) { if (IsDisposed) throw new ObjectDisposedException("ManagedTransientContainerLifecycle"); var instance = registration.Activator.CreateInstance(container); lock (_instancesLock) { _instances.Add(instance); } return instance; }
public void Should_be_able_to_register_an_account() { ICustomer customer = CreateSUT( ); customer.RegisterAccount("username", "password", "mo", "khan", "4036813389", "calgary"); IRegistration registration = customer.Registration( ); Assert.AreEqual("username", registration.Username( )); Assert.AreEqual("password", registration.Password( )); Assert.AreEqual("mo", registration.FirstName( )); Assert.AreEqual("khan", registration.LastName( )); Assert.AreEqual("4036813389", registration.PhoneNumber( )); Assert.AreEqual("calgary", registration.City( )); }
public void AddRegistration(IRegistration registration) { if (registration == null) { throw new ArgumentNullException($"{nameof(registration)} cannot be null"); } if (!allPlans.ContainsKey(registration.DefinedType)) { allPlans[registration.DefinedType] = new HashSet <ConstructionPlan>(); } allPlans[registration.DefinedType].Add(new ConstructionPlan(registration, allPlans, constructorSelectionStrategy)); }
public static IRegistration Register <A, B, C, R>(this IRegistration registration, Func <A, B, C, R> source) { var targetType = typeof(Func <C, R>); var curried = Functional.Curry(source); registration.Add(targetType, () => curried( registration.Get <A>() ) ( registration.Get <B>() )); return(registration); }
/// <summary> /// Adds the function to resolve the unnamed registration of the specified type to the container. This /// also performs provider initialization and instanciation. /// </summary> /// <typeparam name="TProviderBaseType">The base type provider</typeparam> /// <param name="providerInstance">The instance of the provider. Must be a sub-class of base type provider.</param> /// <returns>An IRegistration that can be used to configure the behavior of the registration.</returns> public IRegistration Register <TProviderBaseType>(Provider providerInstance) { var providerBaseType = typeof(TProviderBaseType); var providerType = providerInstance.GetType(); providerInstance.Initialize(providerType.Name, null); // Make sure we have only one instance of the provider, that's why we are calling RegisterInstance IRegistration registration = RegisterInstance(providerBaseType, providerInstance); // Invoke the registration event Service.InvokeProviderRegistered(new ProviderRegisteredEventArgs(providerBaseType, providerInstance)); return(registration); }
public void Register(TypeMap typeMap, ITypeMapCollection dependencies = null, bool isComposite = false) { var serviceType = typeMap.ServiceType; var concreteType = typeMap.ConcreteType; IRegistration compositeRegistration = null; var castAs = serviceType.GetTypeFromAttribute(); var disposable = serviceType.GetDisposableFromAttribute(); compositeRegistration = isComposite ? new CompositeTypeRegistration(container, typeMap, dependencies, castAs, disposable) : new CompositeFrameworkRegistration(container, typeMap, dependencies, castAs, disposable); container.Register(compositeRegistration); }
public void Install(IWindsorContainer container, IConfigurationStore store) { IWindsorContainer iwindsorContainer = container; IRegistration[] iregistrationArray = new IRegistration[1]; int index = 0; ComponentRegistration <ITaskFactory> componentRegistration1 = Component.For <ITaskFactory>(); int num = 0; ComponentRegistration <ITaskFactory> componentRegistration2 = componentRegistration1.UsingFactoryMethod(kernel => new TaskFactory(kernel), num != 0); iregistrationArray[index] = componentRegistration2; iwindsorContainer.Register(iregistrationArray); }
/// <summary> /// Replaces the current <see cref="Registration"/> with the <paramref name="newRegistration"/>. /// </summary> /// <param name="newRegistration">The new <see cref="IRegistration"/>.</param> /// <returns>The old <see cref="IRegistration"/>.</returns> public IRegistration Replace(IRegistration newRegistration) { if (newRegistration == null) { throw new ArgumentNullException(nameof(newRegistration)); } newRegistration.Internal = _internal; IRegistration oldRegistration = Registration; Registration = newRegistration; return(oldRegistration); }
/// <summary> /// Add registration to cache. /// </summary> /// <param name="registration">Registration to add.</param> private void addRegistration(IRegistration registration) { if (typeIsRegistered(registration.RegisteredType)) { if (Options.ThrowExceptionOnDuplicateRegistration) { Type type = registration.RegisteredType; throw new DuplicateRegistrationException(type, $"{type.Name} is already registered."); } } _registrations.Add(registration.RegisteredType, registration); }
/// <summary> /// This is used to make an http proxy and to active it. /// </summary> /// <param name="EndpoindAddress"></param> /// <param name="callbackinstance"></param> public void MakeClient(string EndpoindAddress, object callbackinstance) { WSDualHttpBinding namedpipebinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None); EndpointAddress endpointAddress = new EndpointAddress(EndpoindAddress); InstanceContext context = new InstanceContext(callbackinstance); m_Proxy = new RegistrationProxy(context, namedpipebinding, endpointAddress); /* string strHostName = Dns.GetHostName(); * IPHostEntry ipEntry = Dns.GetHostByName(strHostName); * IPAddress[] addr = ipEntry.AddressList;*/ // namedpipebinding.ClientBaseAddress = new Uri("http://" + addr[0].ToString() + ":" + "4000" + "/"); //namedpipebinding.ClientBaseAddress = }
/// <summary> /// Updates secret details of the registration account. /// </summary> /// <param name="registration">Registration Information of the user.</param> public void UpdateSecretDetails(RegistrationInfo registration) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { dao.UpdateSecretDetails(registration); } catch { throw; } }
/// <summary> /// Updates the status of the specified registration account. /// </summary> /// <param name="userId">Internal identifier of the user.</param> /// <param name="status">Status of the user.</param> public void UpdateStatus(int userId, RegistrationStatus status, int userLoginId) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { dao.UpdateStatus(userId, status, userLoginId); } catch { throw; } }
/// <summary> /// Updates a registration account. /// </summary> /// <param name="registration">Registration Information of the user.</param> public void Update(RegistrationInfo registration, int userLoginId) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { dao.Update(registration, userLoginId); } catch { throw; } }
/// <summary> /// Updates the credit card details of the specified registration account. /// </summary> /// <param name="userId">Internal identifier of the user.</param> /// <param name="creditCard">Credit Card Information of the user.</param> public void UpdateCreditCard(int userId, CreditCardInfo creditCard) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { dao.UpdateCreditCard(userId, creditCard); } catch { throw; } }
/// <summary> /// Gets the instance from cache, if available, otherwise creates a new /// instance and caches it. /// </summary> /// <param name="registration">The creator (registration) to create a new instance.</param> /// <returns>The instance.</returns> public object GetInstance(IRegistration registration) { Cache cache = HttpRuntime.Cache; string key = registration.Key; object instance = cache[key]; if (instance == null) { lock (_lock) { instance = cache[key]; if (instance == null) { instance = registration.CreateInstance(); if (_expiresOn == Cache.NoAbsoluteExpiration && _duration == Cache.NoSlidingExpiration) { _expirationKind = Expires.None; } switch (_expirationKind) { case Expires.None: cache.Insert(key, instance, _dependencies, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.OnDateTime: cache.Insert(key, instance, _dependencies, _expiresOn, Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.AfterFixedDuration: cache.Insert(key, instance, _dependencies, DateTime.Now.Add(_duration), Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.AfterSlidingDuration: cache.Insert(key, instance, _dependencies, Cache.NoAbsoluteExpiration, _duration, _priority, _onRemoveCallback); break; } } } } return(instance); }
private static IRegistration[] ProcessTypesToRegister <T>(this IKernel containerKernel, List <Type> typesToRegister, bool asSingletons = false) { var registrations = new IRegistration[typesToRegister.Count]; for (var i = 0; i < typesToRegister.Count; i++) { var usingFactoryMethod = typeof(RegisterExtensionMethods) .GetMethod(nameof(RegisterComponentForProxy), BindingFlags.NonPublic | BindingFlags.Static); var usingFactoryMethodRef = usingFactoryMethod.MakeGenericMethod(typeof(T), typesToRegister[i]); registrations[i] = usingFactoryMethodRef .Invoke(new BusinessLayerInstaller(), new object[] { containerKernel, asSingletons }) as IRegistration; } return(registrations); }
public bool TryGet(Type interfaceType, out IRegistration registration) { if (hashTable.TryGet(interfaceType, out registration)) { return(registration != null); } if (interfaceType.IsConstructedGenericType) { var genericType = interfaceType.GetGenericTypeDefinition(); return(TryFallbackSingleCollection(interfaceType, genericType, out registration)); } return(false); }
protected virtual Expression CompileRegistrationIntoExpression(IRegistration registration) { if (registration == null) { throw new ArgumentNullException("registration"); } // Check if it is an InstanceRegistration<> if (ReflectionHelper.IsInstanceOfGenericType(typeof(InstanceRegistration <>), registration) && _targetRegistration.CompileMode == CompileMode.Delegate) { var instance = registration.GetInstance(); return(ConstantExpression.Constant(instance)); } // Check if it is an IExpressionRegistration var expReg = registration as IExpressionRegistration; if (expReg != null) { // Check if the lifetime can be compiled if (expReg.Lifetime is TransientLifetime) { // Keep visiting and try to inline the expression of the Registration found // Recursive call until deepest nested ExpressionRegistration with TransientLifetime is found // About to visit a child to the current - current becomes parent and registration/child to visit becomes current var parent = _currentVisitedRegistration; _currentVisitedRegistration = expReg; // Visit - visit the body and return it so it is inlined within the original Expression<Func<IResolver, object>> var expression = Visit(expReg.Expression.Body); // Returned from visiting child - change it back again _currentVisitedRegistration = parent; return(expression); } if (expReg.Lifetime is ContainerLifetime && _targetRegistration.CompileMode == CompileMode.Delegate) { var instance = expReg.GetInstance(); return(ConstantExpression.Constant(instance)); } } // Returning null will make it keep visiting return(null); }
private List <ConstructorDependency> GetConstructorDependencies(ConstructorInfo constructor) { return(constructor.GetParameters().Select(param => { IRegistration ctorDependencyRegistration = Container.GetRegistration(param.ParameterType); if (ctorDependencyRegistration == null) { throw new MissingDependencyException(param.ParameterType, $"{param.ParameterType.Name} is required by {ImplementationType.Name}, but was not registered in the container."); } return new ConstructorDependency(Constructor, ctorDependencyRegistration); }) .ToList()); }
/// <inheritdoc/> void IDisposable.Dispose() { //Dispose can be called from different Threads //CEF maintains a reference and the user //maintains a reference, we in a rare case //we end up disposing of #3725 twice from different //threads. This will ensure our dispose only runs once. if (Interlocked.Increment(ref disposeCount) == 1) { DevToolsEvent = null; devToolsRegistration?.Dispose(); devToolsRegistration = null; browser = null; } }
/// <summary> /// Inserts a registration account with user Work Space Area. /// </summary> /// <param name="registration">Registration Information of the user.</param> /// <param name="workSpacePath">String Path in which Workspase Directory</param> public int InsertWithWorkSpaceDirectory(RegistrationInfo registration, string workSpacePath) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { int userId = dao.InsertWithWorkSpaceDirectory(registration, workSpacePath); return(userId); } catch { throw; } }
/// <summary> /// Inserts a registration account. /// </summary> /// <param name="registration">Registration Information of the user.</param> public int Insert(RegistrationInfo registration) { // Get an instance of the Registration DAO using the DALFactory IRegistration dao = (IRegistration)DALFactory.DAO.Create(DALFactory.Module.Registration); try { int userId = dao.Insert(registration); return(userId); } catch { throw; } }
private List <PropertyDependency> GetPropertyDependencies(IEnumerable <PropertyInfo> injectableProperties) { return(injectableProperties.Select(prop => { IRegistration propDependencyRegistration = Container.GetRegistration(prop.PropertyType); if (propDependencyRegistration == null) { throw new MissingDependencyException(prop.PropertyType, $"{prop.PropertyType.Name} is required by {ImplementationType.Name}, but was not registered in the container."); } return new PropertyDependency(prop, propDependencyRegistration); }) .ToList()); }
public Engine (IPlayerCreator playerCreator, IGameController gameController, IRegistration player, IWriter writer, IReader reader, IApplicationInterface applicationInterface) { this.playerCreator = playerCreator; this.gameController = gameController; this.player = player; this.Reader = reader; this.applicationInterface = applicationInterface; this.Writer = writer; }
protected override ServiceEntry CreateServiceEntry(IRegistration registration) { if (registration.Is <CompositeTypeRegistration>()) { return(new CompositeServiceEntry { Container = this, Owner = registration.Owner, Factory = registration.Func, Lifetime = registration.Lifetime, LifetimeStrategy = registration.Lifetime.ToStrategy(this) }); } return(base.CreateServiceEntry(registration)); }
public void Should_leverage_mapper_to_load_customer_registration() { long customerId = 59; IRegistration registration = _mockery.DynamicMock <IRegistration>( ); using (_mockery.Record( )) { Expect.Call(_registrationMapper.For(customerId)).Return(registration); } using (_mockery.Playback( )) { ICustomer customer = CreateSUT( ).FindBy(customerId); Assert.AreEqual(registration, customer.Registration( )); } }
public bool Exists(IRegistration registration) { if (registration.InterfaceTypes?.Count > 0) { foreach (var type in registration.InterfaceTypes) { if (hashTable.TryGet(type, out _)) { return(true); } } return(false); } return(hashTable.TryGet(registration.ImplementationType, out _)); }
/// <summary> /// Gets the instance from cache, if available, otherwise creates a new /// instance and caches it. /// </summary> /// <param name="registration">The creator (registration) to create a new instance.</param> /// <returns>The instance.</returns> public object GetInstance(IRegistration registration) { Cache cache = HttpRuntime.Cache; string key = registration.Key; object instance = cache[key]; if (instance == null) { lock (_lock) { instance = cache[key]; if (instance == null) { instance = registration.CreateInstance(); if (_expiresOn == Cache.NoAbsoluteExpiration && _duration == Cache.NoSlidingExpiration) _expirationKind = Expires.None; switch (_expirationKind) { case Expires.None: cache.Insert(key, instance, _dependencies, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.OnDateTime: cache.Insert(key, instance, _dependencies, _expiresOn, Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.AfterFixedDuration: cache.Insert(key, instance, _dependencies, DateTime.Now.Add(_duration), Cache.NoSlidingExpiration, _priority, _onRemoveCallback); break; case Expires.AfterSlidingDuration: cache.Insert(key, instance, _dependencies, Cache.NoAbsoluteExpiration, _duration, _priority, _onRemoveCallback); break; } } } } return instance; }
protected (IReadOnlyList <IRegistration>, IReadOnlyList <(IRegistration, Action <IRegistration, IObjectResolver>)>) BuildRegistrations() { var registrations = new IRegistration[registrationBuilders.Count + (ContainerExposed ? 1 : 0)]; var callbacks = new List <(IRegistration, Action <IRegistration, IObjectResolver>)>(registrations.Length); #if VCONTAINER_PARALLEL_CONTAINER_BUILD Parallel.For(0, registrationBuilders.Count, i => { var registrationBuilder = registrationBuilders[i]; var registration = registrationBuilder.Build(); registrations[i] = registration; if (registrationBuilder.BuildCallback is Action <IRegistration, IObjectResolver> callback) { callbacks.Add((registration, callback)); } }); #else for (var i = 0; i < registrationBuilders.Count; i++) { var registrationBuilder = registrationBuilders[i]; var registration = registrationBuilder.Build(); registrations[i] = registration; if (registrationBuilder.BuildCallback is Action <IRegistration, IObjectResolver> callback) { callbacks.Add((registration, callback)); } } #endif if (ContainerExposed) { registrations[registrations.Length - 1] = ContainerRegistration.Default; } #if VCONTAINER_PARALLEL_CONTAINER_BUILD Parallel.For(0, registrations.Count, i => { TypeAnalyzer.CheckCircularDependency(registrations[i].ImplementationType); }); #else foreach (var x in registrations) { TypeAnalyzer.CheckCircularDependency(x.ImplementationType); } #endif return(registrations, callbacks); }
/// <summary> /// Gets an instance from the thread local storage, or creates a new instance if not found. /// </summary> /// <param name="creator">The IInstanceCreate to use to get the Key and create new if required.</param> /// <returns>The instance.</returns> public object GetInstance(IRegistration creator) { object instance = null; // if it is a new thread then the localStorage needs to be initialized; if (localStorage == null) localStorage = new Dictionary<string,object>(); if (!localStorage.TryGetValue(creator.Key, out instance)) { instance = creator.CreateInstance(); localStorage[creator.Key] = instance; } return instance; }
public void Should_be_able_to_update_record() { IRegistrationDataMapper mapper = CreateSUT( ); long customerId = CreateCustomerRecord( ); IRegistration firstRegistration = new CustomerRegistration("mokhan", "password", "mo", "khan", "4036813389", "calgary"); IRegistration expectedRegistration = new CustomerRegistration("khanmo", "wordpass", "om", "ankh", "1338940368", "garycal"); mapper.Insert(firstRegistration, customerId); mapper.Update(expectedRegistration, customerId); IRegistration actualRegistration = mapper.For(customerId); Assert.AreEqual(expectedRegistration, actualRegistration); }
public void Add(Type type, IRegistration registration) { if (!registrations.ContainsKey(type)) { var list = new List<IRegistration>(); registrations.Add(type, list); } var selectedRegistration = GetRegistrationsForType(type); if (selectedRegistration.Contains(registration)) return; selectedRegistration.Add(registration); this.registrations[type] = selectedRegistration; this.addedRegistrations.Add(registration); }
public override void Add(IRegistration registration) { var namedRegistration = registration as INamedRegistration; var registrationMap = new Dictionary<Type, INamedRegistration>(); if(namedRegistrations.ContainsKey(namedRegistration.Key)) { registrationMap = namedRegistrations[namedRegistration.Key]; } if(!registrationMap.ContainsKey(namedRegistration.GetMappedFromType())) registrationMap.Add(namedRegistration.GetMappedFromType(), namedRegistration); namedRegistrations[namedRegistration.Key] = registrationMap; base.Add(registration); }
public void Add(IRegistration registration) { GroupedEntry entry; if (_index.TryGetValue(registration.Type, out entry)) { // Add to already existing entry entry.Add(registration); } else { // Add new entry entry = new GroupedEntry(); entry.Add(registration); _index.Add(registration.Type, entry); } }
private static Expression buildDependencyGetInstanceExpression(IRegistration dependentRegistration, Dependency dependency) { // Constant. // Resulting expression: IRegistration registration = dependency; ConstantExpression instanceExpression = Expression.Constant( dependency.Registration, RegistrationType); // Create expression that call's registration's GetInstance() method. // Resulting expression: registration.GetInstance(); MethodCallExpression callGetInstanceExpression = Expression.Call(instanceExpression, GetInstanceMethod); // Cast GetInstance() result to the registration's implementation type. // Resulting expression: (TestService)registration.GetInstance(); return(Expression.Convert(callGetInstanceExpression, dependency.Registration.ImplementationType)); }
private Expression HandleMethodCall(Type type, object key = null) { // Simple protection against infinite loop // Assumes infinit loop if more than 10000 visits if (_visitCount >= 10000) { throw new InvalidOperationException("Registration for/including " + FormatTypeKeyMessage(type, key) + " caused an infinite loop."); } _visitCount++; // Lookup the registration IRegistration registration = GetRegistration(type, key); return(CompileRegistrationIntoExpression(registration)); }
protected virtual Expression CompileRegistrationIntoExpression(IRegistration registration) { if (registration == null) throw new ArgumentNullException("registration"); // Check if it is an InstanceRegistration<> if (ReflectionHelper.IsInstanceOfGenericType(typeof(InstanceRegistration<>), registration) && _targetRegistration.CompileMode == CompileMode.Delegate) { var instance = registration.GetInstance(); return ConstantExpression.Constant(instance); } // Check if it is an IExpressionRegistration var expReg = registration as IExpressionRegistration; if (expReg != null) { // Check if the lifetime can be compiled if (expReg.Lifetime is TransientLifetime) { // Keep visiting and try to inline the expression of the Registration found // Recursive call until deepest nested ExpressionRegistration with TransientLifetime is found // About to visit a child to the current - current becomes parent and registration/child to visit becomes current var parent = _currentVisitedRegistration; _currentVisitedRegistration = expReg; // Visit - visit the body and return it so it is inlined within the original Expression<Func<IResolver, object>> var expression = Visit(expReg.Expression.Body); // Returned from visiting child - change it back again _currentVisitedRegistration = parent; return expression; } if (expReg.Lifetime is ContainerLifetime && _targetRegistration.CompileMode == CompileMode.Delegate) { var instance = expReg.GetInstance(); return ConstantExpression.Constant(instance); } } // Returning null will make it keep visiting return null; }
public IRegistration Process(IRegistration registration) { var allMetaRegistrations = locator.GetAllInstances<IMetaRegistration>(); var previousRegistration = registration; foreach(IMetaRegistration metaRegistration in allMetaRegistrations) { if(metaRegistration.IsValid(registration)) { metaRegistration.ChainTo(previousRegistration); previousRegistration = metaRegistration; } } return previousRegistration; }