protected void EnsureValidDependenciesLifetime( ConstructorInfo constructor, DependencyLifetime dependedLifetime, IDependencyEngine engine) { var parameters = constructor.GetParameters(); foreach (var parameter in parameters) { var dependencyType = parameter.ParameterType; var dependency = parameter.IsOptional ? engine.GetDependency(dependencyType) : engine.GetRequiredDependency(dependencyType); if (dependency == null) { continue; } var dependencyLifetime = dependency.Lifetime; if (dependedLifetime == DependencyLifetime.Singleton && dependencyLifetime == DependencyLifetime.Scoped) { throw Error.InconsistentLifetime(Implementation, dependedLifetime, dependencyType, dependencyLifetime); } } }
/// <summary> /// Adds a dependency of type <typeparamref name="TService"/>, implemented by the type <typeparamref name="TConcrete"/>, with the specified dependency lifetime. /// </summary> /// <typeparam name="TService">The type to register.</typeparam> /// <typeparam name="TConcrete">The type of the concrete implementation.</typeparam> /// <param name="resolver">The resolver.</param> /// <param name="lifetime">The lifetime of the type.</param> public static void AddDependency <TService, TConcrete>(this IDependencyResolver resolver, DependencyLifetime lifetime) where TService : class where TConcrete : class, TService { resolver.AddDependency(typeof(TService), typeof(TConcrete), lifetime); }
protected static Mock <IDependency>[] SetupApplicableDependencies( Mock <IDependencyEngine> dependencyEngine, Type type, DependencyLifetime lifetime = DependencyLifetime.Singleton, int count = 10) { var dependencies = Enumerable .Range(0, count) .Select(_ => new Mock <IDependency>()) .Do(dependency => dependency .SetupGet(d => d.Lifetime) .Returns(lifetime)) .Do(dependency => dependency .SetupGet(d => d.Implementation) .Returns(type)) .ToArray(); dependencyEngine .Setup(engine => engine.Contains(type)) .Returns(true); dependencyEngine .Setup(engine => engine.GetApplicable(type)) .Returns(dependencies.Select(d => d.Object).ToArray()); return(dependencies); }
public static DependencyCollection AddHttpHandler <THandler>(this DependencyCollection dependencies, DependencyLifetime lifetime = DependencyLifetime.Singleton) where THandler : class, IHttpRequestHandler { dependencies.AddDependency(Typeof <IHttpRequestHandler> .Raw, typeof(THandler), lifetime); return(dependencies); }
public ServiceItem(PluginContainer parent, Type type, object value) { Parent = parent; Type = type; Lifetime = DependencyLifetime.Singleton; _value = value; }
private static void SetupLifetime <TLimit, TActivatorData, TRegistrationStyle>( IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> builder, DependencyLifetime lifetime, object[] lifetimeScopes) { switch (lifetime) { case DependencyLifetime.InstanceSingle: builder.SingleInstance(); break; case DependencyLifetime.InstancePerDependency: builder.InstancePerDependency(); break; case DependencyLifetime.InstancePerLifetimeScope: builder.InstancePerLifetimeScope(); break; case DependencyLifetime.InstancePerMatchingLifetimeScope: builder.InstancePerMatchingLifetimeScope(lifetimeScopes); break; case DependencyLifetime.InstancePerRequest: builder.InstancePerRequest(); break; default: throw new ArgumentOutOfRangeException(); } }
public DependencyCollection AddDependency <TResult>( Type[] contracts, Func <IServiceProvider, TResult> builder, DependencyLifetime lifetime) where TResult : class { var implementation = typeof(TResult); foreach (var contract in contracts) { if (contract.IsAssignableFrom(implementation)) { continue; } var contractName = ReflectionUtils.GetName(contract); var resultName = ReflectionUtils.GetName <TResult>(); throw Error.InvalidOperation($"Type {resultName} is not assignable from {contractName}"); } var resolver = new DelegateResolver <TResult>(builder); var dependency = Dependency.Build(lifetime, contracts, resolver); return(Add(dependency)); }
private LifetimeManager CreateLifetimeManager(DependencyLifetime lifetime, bool isMappedToType) { if (lifetime.IsTransient) { return(new TransientLifetimeManager()); } if (lifetime.IsNamed) { if (isMappedToType) { return(new ContainerControlledLifetimeManager()); } return(new ExternallyControlledLifetimeManager()); } if (lifetime.IsScoped) { return(new HierarchicalLifetimeManager()); } // Not supported lifetime. throw Ensure.Exception.NotSupported(lifetime.ToString()); }
protected static Mock <IDependency> MockDependency( DependencyLifetime lifetime = DependencyLifetime.Singleton, Type contract = null) { var dependency = new Mock <IDependency>(); dependency .SetupGet(d => d.Lifetime) .Returns(lifetime); // ReSharper disable once InvertIf if (contract != null) { dependency .Setup(d => d.Applicable(contract)) .Returns(true); dependency .SetupGet(d => d.Contracts) .Returns(new[] { contract }); dependency .SetupGet(d => d.Implementation) .Returns(contract); } return(dependency); }
public void AddDependency(Type concreteType, DependencyLifetime lifetime) { CheckConcreteType(concreteType); CheckLifetime(lifetime); AddDependencyCore(concreteType, lifetime); }
public async Task PublishedWithDifferentLifetimes( Notification[] notifications, DependencyLifetime commandProcessorLifetime, DependencyLifetime notificationProcessorLifetime) { var dependencyCollection = new DependencyCollection(); var provider = dependencyCollection .AddInstance(_fooRepository.Object) .AddCommandProcessor <Processor>(commandProcessorLifetime) .AddNotificationProcessor <OnBooCreated>(notificationProcessorLifetime) .AddEmitter() .BuildProvider(); dependencyCollection.GetLifetime <NotificationPipeline <Notification> >().Should().Be(notificationProcessorLifetime); var emitter = provider.GetRequiredService <Emitter>(); foreach (var notification in notifications) { notification.StopPropagation = false; await emitter.Publish(notification); _fooRepository.Verify(repository => repository .AddElement(It.Is <Foo>(foo => foo.Int == notification.Id))); } }
public static DependencyScanner RegisterSystems( this DependencyScanner scanner, DependencyLifetime lifetime = DependencyLifetime.Singleton) { scanner.UseCollector(new SystemsCollector(lifetime)); return(scanner); }
public static DependencyCollection AddHttpHandler(this DependencyCollection collection, Func <IDependencyScope, IHttpRequestHandler> builder, DependencyLifetime lifetime = DependencyLifetime.Singleton) { collection.AddDependency(builder, lifetime); return(collection); }
protected override void AddDependencyCore(Type dependent, Type concrete, DependencyLifetime lifetime) { string componentName = Guid.NewGuid().ToString(); if (lifetime != DependencyLifetime.PerRequest) { #if CASTLE_20 _windsorContainer.AddComponentLifeStyle(componentName, dependent, concrete, ConvertLifestyles.ToLifestyleType(lifetime)); #elif CASTLE_10 _windsorContainer.AddComponentWithLifestyle(componentName, dependent, concrete, ConvertLifestyles.ToLifestyleType(lifetime)); #endif } else { #if CASTLE_20 _windsorContainer.Register( Component.For(dependent).Named(componentName).ImplementedBy(concrete).LifeStyle.Custom(typeof(ContextStoreLifetime))); #elif CASTLE_10 ComponentModel component = _windsorContainer.Kernel.ComponentModelBuilder.BuildModel(componentName, dependent, concrete, null); component.LifestyleType = ConvertLifestyles.ToLifestyleType(lifetime); component.CustomLifestyle = typeof(ContextStoreLifetime); _windsorContainer.Kernel.AddCustomComponent(component); #endif } }
public ServiceScopeDependency() { Implementation = typeof(ServiceScope); Lifetime = DependencyLifetime.Transient; _scopeFactoryType = typeof(IServiceScopeFactory); }
public IDependencyRegistrar Type(Type from, Type to, DependencyLifetime lifetime) { var lifetimeManager = CreateLifetimeManager(lifetime); _unityContainer.RegisterType(from, to, lifetimeManager); return(this); }
public void GetDependencyLifetime(DependencyLifetime lifetime) { var dependency = MockDependency(lifetime, _contract).Object; _dependencies.Add(dependency); _dependencies.GetLifetime(_contract).Should().Be(lifetime); }
/// <summary> /// Registers a custom dependency that can be used for leveraging dependency injection. /// </summary> /// <typeparam name="TService">The type of the service to register</typeparam> /// <typeparam name="TConcrete">The concrete type used when the service type is requested</typeparam> /// <param name="anchor"></param> /// <param name="lifetime">The lifetime of the object.</param> public static void CustomDependency <TService, TConcrete>(this IUses anchor, DependencyLifetime lifetime = DependencyLifetime.Singleton) where TConcrete : TService { var fluentTarget = (IFluentTarget)anchor; fluentTarget.Repository.CustomRegistrations.Add( new DependencyRegistrationModel(typeof(TService), typeof(TConcrete), lifetime)); }
public DependencyRegistrationModel(Type serviceType, Type concreteType, DependencyLifetime lifetime) { if (serviceType == null) throw new ArgumentNullException("serviceType"); if (concreteType == null) throw new ArgumentNullException("concreteType"); ServiceType = serviceType; ConcreteType = concreteType; Lifetime = lifetime; }
public void CreateWithValidLifetime(DependencyLifetime lifetime) { SetupApplicableDependencies(_engine, _processorType, lifetime); var dependency = _factory.BuildDependency(_pipelineType, _engine.Object); dependency.Lifetime.Should().Be(lifetime); }
protected static void CheckLifetime(DependencyLifetime lifetime) { if (!Enum.IsDefined(typeof(DependencyLifetime), lifetime)) { throw new InvalidOperationException( $"Value {lifetime} is unknown for enumeration DependencyLifetime."); } }
public void BuildWithValidLifetime(DependencyLifetime lifetime) { var factory = new GenericFactory(_genericContract, _genericImplementation, lifetime); var dependency = factory.BuildDependency(_genericContract.MakeGenericType(typeof(int)), _engine); dependency.Lifetime.Should().Be(lifetime); }
public void CreateWithValidLifetime(DependencyLifetime lifetime) { SetupRequiredDependency(_engine, typeof(ICommandProcessor <Command>), lifetime); var dependency = _factory.BuildDependency(_pipelineType, _engine.Object); dependency.Lifetime.Should().Be(lifetime); }
public void CreateWithValidLifetime(DependencyLifetime lifetime) { SetupApplicable(_engine, _systemType, MockDependency(lifetime).Object); var dependency = _factory.BuildDependency(_handlerType, _engine.Object); dependency.Lifetime.Should().Be(lifetime); }
public void AddQueryBehaviour(DependencyLifetime lifetime) { _dependencies.AddQueryBehaviour <TestsModels.Emitting.Boos.Get.Behaviour>(lifetime); var behaviourType = typeof(TestsModels.Emitting.Boos.Get.Behaviour); _dependencies.Contains(behaviourType).Should().BeTrue(); _dependencies.GetLifetime(behaviourType).Should().Be(lifetime); }
public void AddQueryProcessor(DependencyLifetime lifetime) { _dependencies.AddQueryProcessor <TestsModels.Emitting.Boos.Get.Processor>(lifetime); var processorType = typeof(TestsModels.Emitting.Boos.Get.Processor); _dependencies.Contains(processorType).Should().BeTrue(); _dependencies.GetLifetime(processorType).Should().Be(lifetime); }
public void AddDependencyWithBuilder(DependencyLifetime lifetime) { var contracts = new[] { _contract }; var builder = Mock.Of <Func <IServiceProvider, BooRepository> >(); _dependencies.AddDependency(contracts, builder, lifetime); _dependencies.Contains(_contract).Should().BeTrue(); }
public DependencyDefinition(Type requiredType, DependencyLifetime lifetime, object target) { Ensure.NotNull(requiredType, "requiredType"); Ensure.NotNull(target, "target"); RequiredType = requiredType; Lifetime = lifetime; Target = target; DependencyProperties = new List <PropertyInfo>(); }
public IDependencyRegistrar Type <TFrom, TTo>(DependencyLifetime lifetime) where TTo : TFrom { var lifetimeManager = CreateLifetimeManager(lifetime); _unityContainer.RegisterType <TFrom, TTo>(lifetimeManager); return(this); }
public static DependencyCollection AddHttpHandler(this DependencyCollection dependencies, Func <IServiceProvider, IHttpRequestHandler> builder, DependencyLifetime lifetime = DependencyLifetime.Singleton) { var contracts = new[] { typeof(IHttpRequestHandler) }; dependencies.AddDependency(contracts, builder, lifetime); return(dependencies); }
public DependencyDefinition(Type requiredType, DependencyLifetime lifetime, object target, bool isResolvable = false) { Ensure.NotNull(requiredType, "requiredType"); Ensure.NotNull(target, "target"); RequiredType = requiredType; Lifetime = lifetime; Target = target; IsResolvable = isResolvable; }
public static InstanceScope From(DependencyLifetime lifetime) { InstanceScope result; switch (lifetime) { case DependencyLifetime.PerRequest: result = InstanceScope.PerRequest; break; case DependencyLifetime.Singleton: result = InstanceScope.Singleton; break; case DependencyLifetime.Transient: result = InstanceScope.Transient; break; default: result = InstanceScope.Hybrid; break; } return result; }
public static LifestyleType ToLifestyleType(DependencyLifetime lifetime) { if (lifetime == DependencyLifetime.Singleton) { return LifestyleType.Singleton; } if (lifetime == DependencyLifetime.PerRequest) { return LifestyleType.Custom; } if (lifetime == DependencyLifetime.Transient) { return LifestyleType.Transient; } throw new ArgumentOutOfRangeException("lifetime", "The provided lifetime is not recognized."); }
protected DependencyResolution(DependencyLifetime dependencyLifetime) { this.dependencyLifetime = dependencyLifetime; }