/// <summary>
		/// 	Configures component with default service type (first not-IConrainerBound interface) with no name and default Priority/Lifestyle
		/// </summary>
		public ContainerComponentAttribute(Type serviceType = null, Lifestyle lifestyle = Lifestyle.Default, string name = "",
		                                   int priority = -1) {
			Priority = priority; //default component level for manifest (assembly level will be used)
			Lifestyle = lifestyle;
			Name = name;
			ServiceType = serviceType; //will be resolved automatically
		}
 public static void Initialize(Container container, Lifestyle lifestyle)
 {
     container.Register<IProdutoRepository, ProdutoRepository>(lifestyle);
     container.Register<ICompraRepository, CompraRepository>(lifestyle);
     container.Register<ICompraItemRepository, CompraItemRepository>(lifestyle);
     container.Register<IFornecedorRepository, FornecedorRepository>(lifestyle);
 }
Ejemplo n.º 3
0
        private static void Register(Type interfaceType, Lifestyle lifestyle, List<Type> types)
        {
            if (!DuplicateImplementationsExists(types))
            {
                foreach (var type in types)
                {
                    var typeInterface = type.GetInterfaces().First(x => x.Name == interfaceType.Name);

                    var registerOptions = TinyIoCContainer.Current.Register(typeInterface, type);
                    if (lifestyle == Lifestyle.PerRequest)
                        registerOptions.AsMultiInstance();
                    else
                    {
                        registerOptions.AsSingleton();
                    }
                }
            }
            else
            {
                var multiRegisterOptions = TinyIoCContainer.Current.RegisterMultiple(interfaceType, types);
                if (lifestyle == Lifestyle.PerRequest)
                    multiRegisterOptions.AsMultiInstance();
                else
                {
                    multiRegisterOptions.AsSingleton();
                }
            }
        }
        public static Container RegisterItems(Container container, Lifestyle lifeStyle)
        {
            RegisterItemsDataAccess(container, lifeStyle);
            RegisterItemsDataBusiness(container, lifeStyle);


            return container;
        }
Ejemplo n.º 5
0
 public static void Register(Container container, Lifestyle lifestyle)
 {
     //container.RegisterAll<IConexao<T>>(Conexao<T>)>(lifestyle);
     container.Register<ICompraDal, CompraDal>(lifestyle);
     container.Register<ICompraItemDal, CompraItemDal>(lifestyle);
     container.Register<IClienteDal, ClienteDal>(lifestyle);
     container.Register<IFornecedorDal, FornecedorDal>(lifestyle);
 }
 public frmSelectLifestyleAdvanced(Lifestyle objLifestyle, Character objCharacter)
 {
     InitializeComponent();
     LanguageManager.Instance.Load(GlobalOptions.Instance.Language, this);
     _objCharacter = objCharacter;
     _objLifestyle = objLifestyle;
     MoveControls();
 }
 public frmSelectAdvancedLifestyle(Lifestyle objLifestyle, Character objCharacter)
 {
     InitializeComponent();
     LanguageManager.Instance.Load(this);
     _objCharacter = objCharacter;
     _objLifestyle = objLifestyle;
     MoveControls();
 }
Ejemplo n.º 8
0
        public static void RegisterApp(this Container container, Lifestyle lifestyle)
        {
            container.Register<CursoAngularJsContext>(lifestyle);
            container.BatchRegister<ClienteRepository>();
            container.BatchRegister<ClienteApplicationService>();

            ServiceLocator.SetLocatorProvider(
                () => new Adapters.SimpleInjectorServiceLocatorAdapter(container));
        }
 internal TornLifestyleDiagnosticResult(Type serviceType, string description, Lifestyle lifestyle,
     Type implementationType, InstanceProducer[] affectedRegistrations)
     : base(serviceType, description, DiagnosticType.TornLifestyle, DiagnosticSeverity.Warning,
         CreateDebugValue(implementationType, lifestyle, affectedRegistrations))
 {
     this.Lifestyle = lifestyle;
     this.ImplementationType = implementationType;
     this.AffectedRegistrations = new ReadOnlyCollection<InstanceProducer>(affectedRegistrations.ToList());
 }
        internal ExpressionBuildingEventArgs(Type registeredServiceType, Type knownImplementationType, 
            Expression expression, Lifestyle lifestyle)
        {
            this.RegisteredServiceType = registeredServiceType;
            this.KnownImplementationType = knownImplementationType;
            this.Lifestyle = lifestyle;

            this.expression = expression;
        }
        internal ExpressionRegistration(Expression expression, Type implementationType, Lifestyle lifestyle, 
            Container container)
            : base(lifestyle, container)
        {
            Requires.IsNotNull(expression, nameof(expression));
            Requires.IsNotNull(implementationType, nameof(implementationType));

            this.expression = expression;
            this.implementationType = implementationType;
        }
Ejemplo n.º 12
0
 public static void RegisterModelDependencies(this Container container, Lifestyle lifestyle)
 {
     container.Register<AdvertiserAccountService, AdvertiserAccountService>(lifestyle);
     container.Register<CryptographyService, CryptographyService>(lifestyle);
     container.Register<AuthenticationService, AuthenticationService>(lifestyle);
     container.Register<LocationService, LocationService>(lifestyle);
     container.Register<ServiceSolicitationService, ServiceSolicitationService>(lifestyle);
     container.Register<ContractModelService,ContractModelService>(lifestyle);
     container.Register<AdvertisementService, AdvertisementService>(lifestyle);
 }
        public DefaultComponentProfile( String key, Type service, Type implementation,
			Lifestyle lifestyle, Activation activation, IConfiguration configuration )
        {
            m_key = key;
            m_service = service;
            m_implementation = implementation;
            m_lifestyle = lifestyle;
            m_activation = activation;
            m_configuration = configuration;
        }
        public static void Bootstrap(Container container, Lifestyle lifestyle)
        {
            container.RegisterApplicationServices();
            container.RegisterDomainServices();
            container.RegisterRepositories();
            container.RegisterDbContexts(lifestyle);
            container.RegisterUnitsOfWork();

            ServiceLocator.SetLocatorProvider(
                () => new Adapters.SimpleInjectorServiceLocatorAdapter(container));
        }
 internal AmbiguousLifestylesDiagnosticResult(Type serviceType, string description, 
     Lifestyle[] lifestyles, Type implementationType, InstanceProducer diagnosedProducer, 
     InstanceProducer[] conflictingProducers)
     : base(serviceType, description, DiagnosticType.AmbiguousLifestyles, DiagnosticSeverity.Warning,
         CreateDebugValue(implementationType, lifestyles, conflictingProducers))
 {
     this.Lifestyles = new ReadOnlyCollection<Lifestyle>(lifestyles.ToList());
     this.ImplementationType = implementationType;
     this.DiagnosedRegistration = diagnosedProducer;
     this.ConflictingRegistrations = new ReadOnlyCollection<InstanceProducer>(conflictingProducers.ToList());
 }
        private static void RegisterItemsDataAccess(Container container, Lifestyle lifeStyle)
        {
            container.Register<IPersonRepository, PersonRepository>(lifeStyle);
            //container.Register<typeof(AdventureContext), AdventureContext > (lifeStyle);
            container.Register<DbContext, AdventureContext>(lifeStyle);
            container.Register<IUnitOfWork, UnitOfWork>(lifeStyle);

            //builder.RegisterType(typeof(SampleArchContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            //builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest();

        }
 public DecoratorExpressionInterceptorData(Container container, Type serviceType, Type decoratorType,
     Predicate<DecoratorPredicateContext> predicate, Lifestyle lifestyle,
     Func<DecoratorPredicateContext, Type> decoratorTypeFactory = null)
 {
     this.Container = container;
     this.ServiceType = serviceType;
     this.DecoratorType = decoratorType;
     this.DecoratorTypeFactory = this.WrapInNullProtector(decoratorTypeFactory);
     this.Predicate = predicate;
     this.Lifestyle = lifestyle;
 }
        private static void RegisterServices(Container container, Assembly assembly, Lifestyle lifestyle)
        {
            var registrations = assembly.GetExportedTypes()
                                 .Where(t => t.GetInterfaces().Any())
                                 .Select(t => new { Service = t.GetInterfaces().Single(), Implementation = t });

            foreach (var reg in registrations)
            {
                container.Register(reg.Service, reg.Implementation, lifestyle);
            }
        }
Ejemplo n.º 19
0
        public static void Register(Container container, Lifestyle lifeStyleDbContext)
        {
            //Containers.ApplicationServiceContainer.RegisterApplicationService(container);
            container.RegisterApplicationServices();
            container.RegisterDomainServices();
            container.RegisterRepositories();

            container.RegisterDbContexts(lifeStyleDbContext);

            ServiceLocatorConfig(container);
        }
Ejemplo n.º 20
0
 public HybridRegistration(Type serviceType, Type implementationType, Func<bool> test,
     Registration trueRegistration, Registration falseRegistration,
     Lifestyle lifestyle, Container container)
     : base(lifestyle, container)
 {
     this.serviceType = serviceType;
     this.implementationType = implementationType;
     this.test = test;
     this.trueRegistration = trueRegistration;
     this.falseRegistration = falseRegistration;
 }
        internal void AddAppliedDecorator(Type decoratorType, Container container, Lifestyle lifestyle, 
            Expression decoratedExpression, IEnumerable<KnownRelationship> decoratorRelationships = null)
        {
            var registration = new ExpressionRegistration(decoratedExpression, decoratorType,
                lifestyle, container);

            registration.ReplaceRelationships(decoratorRelationships ?? Enumerable.Empty<KnownRelationship>());

            var producer = new InstanceProducer(this.registeredServiceType, registration);

            this.appliedDecorators.Add(new DecoratorInfo(decoratorType, producer));
        }
Ejemplo n.º 22
0
        public static void RegisterPersistenceDependencies(this Container container, Lifestyle lifestyle)
        {
            var connectionStringName = ConfigurationManager.AppSettings["databaseConnection"];
            var conn = System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

            container.Register<VoceViuDbContext>(() => new VoceViuDbContext(conn), lifestyle);
            container.Register<IAdvertiserRepository, AdvertiserRepository>(lifestyle);
            container.Register<IAdministratorRepository, AdministratorRepository>(lifestyle);
            container.Register<ILocationRepository, LocationRepository>(lifestyle);
            container.Register<IServiceSolicitationRepository, ServiceSolicitationRepository>(lifestyle);
            container.Register<IContractModelRepository, ContractModelRepository>(lifestyle);
            container.Register<IAdvertisementRepository, AdvertisementRepository>();
        }
        public void AddGeneric(Type serviceType, Type implementationType,
            Lifestyle lifestyle, Predicate<PredicateContext> predicate)
        {
            this.container.ThrowWhenContainerIsLocked();
            this.ThrowWhenConditionalIsRegisteredInOverridingMode(predicate);

            var provider = new OpenGenericToInstanceProducerProvider(
                serviceType, implementationType, lifestyle, predicate, this.container);

            this.ThrowWhenProviderToRegisterOverlapsWithExistingProvider(provider);

            this.providers.Add(provider);
        }
Ejemplo n.º 24
0
		/// <summary>
		/// 	Initializes a new instance of the <see cref="WellKnownService&lt;T&gt;" /> class.
		/// </summary>
		/// <param name="serviceType"> </param>
		/// <param name="wellKnownTypeName"> Name of the well known type. </param>
		/// <param name="defaultType"> The default type. </param>
		/// <param name="lifestyle"> The lifestyle. </param>
		/// <param name="name"> Asserted name of component </param>
		/// <remarks>
		/// </remarks>
		public WellKnownService(Type serviceType, string wellKnownTypeName, Type defaultType, Lifestyle lifestyle,
		                        string name = null) {
			ServiceType = serviceType;
			WellKnownTypeName = wellKnownTypeName;
			DefaultType = defaultType;
			if (string.IsNullOrEmpty(wellKnownTypeName)) {
				ResolvedWellKnownType = DefaultType;
			}
			else {
				ResolvedWellKnownType = Type.GetType(WellKnownTypeName, false) ?? DefaultType;
			}
			Lifestyle = lifestyle;
			Name = name;
		}
        private void Register(Type serviceType, Type implementationType, Lifestyle lifestyle)
        {
            if (serviceType.IsGenericTypeDefinition) {
                this.container.RegisterOpenGeneric(serviceType, implementationType, lifestyle);
            }
            else {
                this.container.Register(serviceType, implementationType, lifestyle);
            }

            // Registering collections in Simple Injector is done using the RegisterAll overloads, but
            // this forces all elements to be registered at once. For integration scenarios, the
            // AppendToCollection extension method can be used. This allows adding elements to a collection
            // one by one.
            this.container.AppendToCollection(serviceType, implementationType);
        }
        public void Add(Type serviceType, Func<TypeFactoryContext, Type> implementationTypeFactory,
            Lifestyle lifestyle, Predicate<PredicateContext> predicate)
        {
            Requires.IsNotNull(predicate, "only support conditional for now");

            this.container.ThrowWhenContainerIsLocked();

            if (this.UnconditionalProducers.Any())
            {
                throw new InvalidOperationException(
                    StringResources.NonGenericTypeAlreadyRegisteredAsUnconditionalRegistration(serviceType));
            }

            this.providers.Add(new ImplementationTypeFactoryInstanceProducerProvider(serviceType,
                implementationTypeFactory, lifestyle, predicate, this.container));
        }
        public static void RegisterRuntimeDecorator(
            this Container container, Type serviceType, Type decoratorType,
            Lifestyle lifestyle,
            Predicate<DecoratorPredicateContext> runtimePredicate,
            Predicate<DecoratorPredicateContext> compileTimePredicate = null)
        {
            var localContext = new ThreadLocal<DecoratorPredicateContext>();

            compileTimePredicate = compileTimePredicate ?? (context => true);

            Predicate<DecoratorPredicateContext> predicate = c =>
            {
                bool mustDecorate = compileTimePredicate(c);
                localContext.Value = mustDecorate ? c : null;
                return mustDecorate;
            };

            if (lifestyle == null)
            {
                container.RegisterDecorator(serviceType, decoratorType, predicate);
            }
            else
            {
                container.RegisterDecorator(serviceType, decoratorType, lifestyle, predicate);
            }

            container.ExpressionBuilt += (s, e) =>
            {
                bool isDecorated = localContext.Value != null;

                if (isDecorated)
                {
                    Expression decorator = e.Expression;
                    Expression original = localContext.Value.Expression;

                    Expression shouldDecorate = Expression.Invoke(
                        Expression.Constant(runtimePredicate),
                        Expression.Constant(localContext.Value));

                    e.Expression = Expression.Condition(shouldDecorate,
                        Expression.Convert(decorator, e.RegisteredServiceType),
                        Expression.Convert(original, e.RegisteredServiceType));

                    localContext.Value = null;
                }
            };
        }
        public void ReadFrom(XmlElement typeResolutionElement)
        {
            //AbstractType
            Debug.Assert(typeResolutionElement != null, "typeResolutionElement != null");
            var abstractTypeElement = (XmlElement)typeResolutionElement.GetElementsByTagName("AbstractType")[0];
            AbstractType = new RuntimeType();
            AbstractType.ReadFrom(abstractTypeElement);

            //ConcreteType
            Debug.Assert(typeResolutionElement != null, "typeResolutionElement != null");
            var concreteTypeElement = (XmlElement)typeResolutionElement.GetElementsByTagName("ConcreteType")[0];
            ConcreteType = new RuntimeType();
            ConcreteType.ReadFrom(concreteTypeElement);

            //Lifestyle
            if (typeResolutionElement.HasAttribute("Lifestyle"))
                Lifestyle = (Lifestyle)Enum.Parse(typeof(Lifestyle), typeResolutionElement.GetAttribute("Lifestyle"));
        }
Ejemplo n.º 29
0
        public void RegisterFrom(Assembly assembly, Type interfaceType, Lifestyle lifestyle = Lifestyle.PerRequest, bool allowMultipleImplementations = false)
        {
            var types = new List<Type>();
            var genericTypes = assembly.GetTypes()
                                .Where(type =>
                                    type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == interfaceType)).ToList();

            types.AddRange(genericTypes);

            var nonGenericTypes = assembly.GetTypes().Where(type => interfaceType.IsAssignableFrom(type) && type.IsClass);

            types.AddRange(nonGenericTypes);

            if(DuplicateImplementationsExists(types) && !allowMultipleImplementations)
                throw new MultipleImplementaionsNotAllowedException(string.Format("Multiple implementations of {0} is not allowed!", interfaceType.FullName));

            Register(interfaceType, lifestyle, types);
        }
 private static DebuggerViewItem[] CreateDebugValue(Type implementationType, Lifestyle lifestyle,
     InstanceProducer[] affectedRegistrations)
 {
     return new[]
     {
         new DebuggerViewItem(
             name: "ImplementationType", 
             description: implementationType.ToFriendlyName(), 
             value: implementationType),
         new DebuggerViewItem(
             name: "Lifestyle", 
             description: lifestyle.Name, 
             value: lifestyle),
         new DebuggerViewItem(
             name: "Affected Registrations", 
             description: ToCommaSeparatedText(affectedRegistrations), 
             value: affectedRegistrations)
     };
 }
 public DummyRegistration(Lifestyle lifestyle) : base(lifestyle, new Container())
 {
 }
Ejemplo n.º 32
0
        public void Register <TService, TImplementation>(IConstructorSelector selector, Lifestyle lifestyle)
            where TService : class
            where TImplementation : class, TService
        {
            this.RegisterExplicitConstructor <TImplementation>(selector);

            this.container.Register <TService, TImplementation>(lifestyle);
        }
Ejemplo n.º 33
0
 public void Register <T>(string key = DefaultKey, Lifestyle lifestyle = null) where T :
 IDataContext, new()
 {
     Register(key, () => new UnitOfWork(new T()), lifestyle);
 }
Ejemplo n.º 34
0
 public PerThreadRegistration(Lifestyle lifestyle, Container container)
     : base(lifestyle, container)
 {
 }
 public PerThreadRegistration(Lifestyle lifestyle, Container container,
                              Func <TImplementation> instanceCreator = null)
     : base(lifestyle, container)
 {
     this.instanceCreator = instanceCreator;
 }
Ejemplo n.º 36
0
        internal ExpressionRegistration(Expression expression, Type implementationType, Lifestyle lifestyle,
                                        Container container)
            : base(lifestyle, container)
        {
            Requires.IsNotNull(expression, nameof(expression));
            Requires.IsNotNull(implementationType, nameof(implementationType));

            this.expression         = expression;
            this.implementationType = implementationType;
        }
Ejemplo n.º 37
0
 /// <summary>
 ///   Регистрирует все обработчики сообщений из указанных сборок
 /// </summary>
 public static void RegisterAllQueueProcessors(this Container container, Lifestyle lifestyle,
                                               params Assembly[] assemblies)
 {
     RegisterCollection(container, typeof(IProcessor), lifestyle, assemblies);
     RegisterCollection(container, typeof(IProcessorAsync), lifestyle, assemblies);
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Lifestyle to update when editing.
 /// </summary>
 /// <param name="objLifestyle">Lifestyle to edit.</param>
 public void SetLifestyle(Lifestyle objLifestyle)
 {
     _objSourceLifestyle = objLifestyle;
     StyleType           = objLifestyle.StyleType;
 }
Ejemplo n.º 39
0
 protected override void RegisterPlugins <T>(IEnumerable <Assembly> assemblies, Lifestyle style = null) => Container.RegisterPlugins <T>(assemblies, style);
// This will work on both 2.x and 3.x. On 2.x this will override the default implementation because it is in the same namespace as the caller.
        public static void RegisterOpenGeneric(this Container container, Type openGenericServiceType, Type openGenericImplementation, Lifestyle lifestyle)
        {
            bool isSimpleInjector2        = false;
            var  openGenericExtensionType = container.GetType().Assembly.GetType("SimpleInjector.Extensions.OpenGenericRegistrationExtensions");

            if (openGenericExtensionType != null)
            {
// Attempt to find the method to invoke
// OpenGenericRegistrationExtensions.RegisterOpenGeneric(container, openGenericServiceType, openGenericImplementation, lifestyle);
                var method = openGenericExtensionType.GetMethod(
                    "RegisterOpenGeneric",
                    BindingFlags.Static | BindingFlags.Public,
                    null,
                    new Type[] { typeof(Container), typeof(Type), typeof(Type), typeof(Lifestyle) },
                    null);

                if (method != null && !Attribute.IsDefined(method, typeof(ObsoleteAttribute)))
                {
// This is SimpleInjector 2 - Invoke the method
                    isSimpleInjector2 = true;
                    method.Invoke(null, new object[] { container, openGenericServiceType, openGenericImplementation, lifestyle });
                }
            }

            if (!isSimpleInjector2)
            {
                container.Register(openGenericServiceType, openGenericImplementation, lifestyle);
            }
        }
Ejemplo n.º 41
0
 public CustomScopedLifestyle(string name = null) : base(name ?? "Custom")
 {
     this.realLifestyle = Lifestyle.Transient;
 }
Ejemplo n.º 42
0
 public SimpleInjectorConfiguration(Action <Container, object> bootstrapFunction, object additionalParam, Lifestyle lifestyle,
                                    JobHostConfiguration config)
 {
     _bootstrapFunction = bootstrapFunction;
     _additionalParam   = additionalParam;
     _lifestyle         = lifestyle;
     _config            = config;
 }
Ejemplo n.º 43
0
        public static void Register <TService>(Func <TService> generator, bool transient = false) where TService : class
        {
            Lifestyle style = transient ? Lifestyle.Transient : Lifestyle.Singleton;

            _container.Register(generator, style);
        }
 public CustomScopedLifestyle(Lifestyle realLifestyle) : base("Custom " + realLifestyle.Name)
 {
     this.realLifestyle = realLifestyle;
 }
Ejemplo n.º 45
0
 public IBootstrapperModules ThreadLifestyle()
 {
     _container.UseThreadLifestyle();
     _lifestyle = Lifestyle.Thread;
     return(this);
 }
 public CustomLifestyleSelectionBehavior(Lifestyle lifestyle)
 {
     this.lifestyle = lifestyle;
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Lifestyle to update when editing.
 /// </summary>
 /// <param name="objLifestyle">Lifestyle to edit.</param>
 public void SetLifestyle(Lifestyle objLifestyle)
 {
     _objSourceLifestyle = objLifestyle;
 }
 public void Register <TImplementation>(TKey key, Lifestyle lifestyle)
     where TImplementation : TService
 {
     this.Register(typeof(TImplementation), key, lifestyle);
 }
Ejemplo n.º 49
0
        private static void RegisterCollection(Container container, Type interfaceType, Lifestyle lifestyle,
                                               IEnumerable <Assembly> assemblies)
        {
            var typesToRegister = container.GetTypesToRegister(interfaceType, assemblies);

            foreach (var type in typesToRegister)
            {
                var registration = CreateRegistration(container, lifestyle, type);
                container.Collection.Append(interfaceType, registration);
            }
        }
Ejemplo n.º 50
0
 public void AddGeneric(Type serviceType, Type implementationType,
                        Lifestyle lifestyle, Predicate <PredicateContext> predicate)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 51
0
 public void Register <TComponent, TImplementation>(Lifestyle lifestyle) where TImplementation : TComponent
 {
     Register(typeof(TComponent), typeof(TImplementation), lifestyle);
 }
Ejemplo n.º 52
0
        public virtual IComponentRegistry Register(Type dependencyType, Type implementationType, Lifestyle lifestyle)
        {
            Guard.AgainstNull(dependencyType, "dependencyType");
            Guard.AgainstNull(implementationType, "implementationType");

            DependencyInvariant(dependencyType);

            _registeredTypes.Add(dependencyType);

            return(this);
        }
Ejemplo n.º 53
0
 private static void Register(IEnumerable <Type> interfaces, IEnumerable <Type> types, Container container, Lifestyle lifestyle)
 {
     foreach (var @interface in interfaces)
     {
         var type = types.Where(item => item.Name == @interface.Name.Substring(1)).FirstOrDefault();
         if (type != null)
         {
             container.Register(@interface, type, lifestyle);
         }
     }
 }
Ejemplo n.º 54
0
 public CustomRegistration(CreateLifestyleApplier lifestyleCreator, Lifestyle lifestyle,
                           Container container)
     : base(lifestyleCreator, lifestyle, container)
 {
 }
Ejemplo n.º 55
0
 private static void RegisterItemsDataBusiness(Container container, Lifestyle lifeStyle)
 {
     container.Register <IPersonService, PersonService>(lifeStyle);
 }
Ejemplo n.º 56
0
 internal OpenGenericToInstanceProducerProvider(Type serviceType,
                                                Func <TypeFactoryContext, Type> implementationTypeFactory, Lifestyle lifestyle,
                                                Predicate <PredicateContext> predicate, Container container)
 {
     this.ServiceType = serviceType;
     this.ImplementationTypeFactory = implementationTypeFactory;
     this.lifestyle = lifestyle;
     this.Predicate = predicate;
     this.container = container;
 }
Ejemplo n.º 57
0
        private void CheckExistingRegistrations(Type serviceType, Type implementationType, Lifestyle lifeStyle, object instance = null)
        {
            if (_registeredInstances.TryGetValue(serviceType, out var registeredInstance))
            {
                if (instance == null)
                {
                    throw new Exception($"The ServiceType {serviceType} is already registered as the instance {registeredInstance}.");
                }
                if (!ReferenceEquals(registeredInstance, instance))
                {
                    throw new Exception($"The instance {registeredInstance} of type {serviceType} was re-registered as another instance {instance} of type {instance.GetType()}.");
                }
            }
            var currentRegistration = CurrentRegistration(serviceType);

            if (currentRegistration != null)
            {
                if (currentRegistration.Registration.ImplementationType != implementationType)
                {
                    throw new Exception($"The ServiceType {currentRegistration.ServiceType} with lifestyle {currentRegistration.Lifestyle} was re-registered with the different implementation type {implementationType}.");
                }
                if (currentRegistration.Lifestyle != lifeStyle)
                {
                    throw new Exception($"The ServiceType {currentRegistration.ServiceType} with lifestyle {currentRegistration.Lifestyle} was re-registered with the different life style {lifeStyle}.");
                }
            }
        }
Ejemplo n.º 58
0
 public IBootstrapperWebLifestyle WebLifestyle()
 {
     _lifestyle = Lifestyle.Web;
     return(this);
 }
        public void DependencyHasPossibleLifestyleMismatch_NestedHybridSingletonToTransient2_ReportsMismatch()
        {
            // Arrange
            Func <bool> selector = () => true;

            var hybridWithDeeplyNestedTransient = Lifestyle.CreateHybrid(selector,
                                                                         Lifestyle.Singleton,
                                                                         Lifestyle.CreateHybrid(selector,
                                                                                                Lifestyle.Singleton,
                                                                                                Lifestyle.CreateHybrid(selector,
                                                                                                                       Lifestyle.Singleton,
                                                                                                                       Lifestyle.CreateHybrid(selector,
                                                                                                                                              Lifestyle.Singleton,
                                                                                                                                              Lifestyle.CreateHybrid(selector,
                                                                                                                                                                     Lifestyle.Singleton,
                                                                                                                                                                     Lifestyle.Transient)))));

            var dependency =
                CreateRelationship(parent: Lifestyle.Singleton, child: hybridWithDeeplyNestedTransient);

            // Act
            bool result = HasPossibleLifestyleMismatch(dependency);

            // Assert
            Assert.IsTrue(result, "Since the hybrid lifestyle contains a transient lifestyle, this " +
                          "hybrid lifestyle should be considered to be a transient when evaluated on the child.");
        }
Ejemplo n.º 60
0
        public static void Register <TService, TImplementation>(bool transient = false) where TService : class where TImplementation : class, TService
        {
            Lifestyle style = transient ? Lifestyle.Transient : Lifestyle.Singleton;

            _container.Register <TService, TImplementation>(style);
        }