示例#1
0
        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);
                }
            }
        }
示例#2
0
 /// <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);
 }
示例#3
0
文件: TestClass.cs 项目: teoadal/velo
        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);
        }
示例#4
0
 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);
 }
示例#5
0
 public ServiceItem(PluginContainer parent, Type type, object value)
 {
     Parent   = parent;
     Type     = type;
     Lifetime = DependencyLifetime.Singleton;
     _value   = value;
 }
示例#6
0
        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();
            }
        }
示例#7
0
        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));
        }
示例#8
0
        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());
        }
示例#9
0
文件: TestClass.cs 项目: teoadal/velo
        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);
        }
示例#10
0
        public void AddDependency(Type concreteType, DependencyLifetime lifetime)
        {
            CheckConcreteType(concreteType);
            CheckLifetime(lifetime);

            AddDependencyCore(concreteType, lifetime);
        }
示例#11
0
        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)));
            }
        }
示例#12
0
 public static DependencyScanner RegisterSystems(
     this DependencyScanner scanner,
     DependencyLifetime lifetime = DependencyLifetime.Singleton)
 {
     scanner.UseCollector(new SystemsCollector(lifetime));
     return(scanner);
 }
示例#13
0
 public static DependencyCollection AddHttpHandler(this DependencyCollection collection,
                                                   Func <IDependencyScope, IHttpRequestHandler> builder,
                                                   DependencyLifetime lifetime = DependencyLifetime.Singleton)
 {
     collection.AddDependency(builder, lifetime);
     return(collection);
 }
示例#14
0
        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
            }
        }
示例#15
0
        public ServiceScopeDependency()
        {
            Implementation = typeof(ServiceScope);
            Lifetime       = DependencyLifetime.Transient;

            _scopeFactoryType = typeof(IServiceScopeFactory);
        }
示例#16
0
        public IDependencyRegistrar Type(Type from, Type to, DependencyLifetime lifetime)
        {
            var lifetimeManager = CreateLifetimeManager(lifetime);

            _unityContainer.RegisterType(from, to, lifetimeManager);

            return(this);
        }
示例#17
0
        public void GetDependencyLifetime(DependencyLifetime lifetime)
        {
            var dependency = MockDependency(lifetime, _contract).Object;

            _dependencies.Add(dependency);

            _dependencies.GetLifetime(_contract).Should().Be(lifetime);
        }
示例#18
0
        /// <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;
 }
示例#20
0
        public void CreateWithValidLifetime(DependencyLifetime lifetime)
        {
            SetupApplicableDependencies(_engine, _processorType, lifetime);

            var dependency = _factory.BuildDependency(_pipelineType, _engine.Object);

            dependency.Lifetime.Should().Be(lifetime);
        }
示例#21
0
 protected static void CheckLifetime(DependencyLifetime lifetime)
 {
     if (!Enum.IsDefined(typeof(DependencyLifetime), lifetime))
     {
         throw new InvalidOperationException(
                   $"Value {lifetime} is unknown for enumeration DependencyLifetime.");
     }
 }
示例#22
0
        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);
        }
示例#23
0
        public void CreateWithValidLifetime(DependencyLifetime lifetime)
        {
            SetupRequiredDependency(_engine, typeof(ICommandProcessor <Command>), lifetime);

            var dependency = _factory.BuildDependency(_pipelineType, _engine.Object);

            dependency.Lifetime.Should().Be(lifetime);
        }
示例#24
0
        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);
        }
示例#27
0
        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();
        }
示例#28
0
 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>();
 }
示例#29
0
        public IDependencyRegistrar Type <TFrom, TTo>(DependencyLifetime lifetime)
            where TTo : TFrom
        {
            var lifetimeManager = CreateLifetimeManager(lifetime);

            _unityContainer.RegisterType <TFrom, TTo>(lifetimeManager);

            return(this);
        }
示例#30
0
        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;
 }
示例#32
0
 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;
 }
示例#33
0
        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.");
        }
示例#34
0
		protected DependencyResolution(DependencyLifetime dependencyLifetime)
		{
			this.dependencyLifetime = dependencyLifetime;
		}