public async Task ArgumentValidationAsync(IEnumerable <Type> typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, Type manager)
        {
            // Act
            await Container.RegisterType(typeFrom, typeTo, name, lifetimeManager);

            // TODO: Add verification

            //var registeredType = typeFrom ?? typeTo;
            //var registration = Container.Registrations.FirstOrDefault(r => r.RegisteredType == registeredType && r.Name == name);

            //Assert.IsNotNull(registration);
            //Assert.IsInstanceOfType(registration.LifetimeManager, manager);
        }
        public async Task ArgumentValidationAsyncFailing(Type exception, IEnumerable <Type> typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
        {
            try
            {
                // Act
                await Container.RegisterType(typeFrom, typeTo, name, lifetimeManager, injectionMembers);

                Assert.Fail($"Did not throw and exception of type {exception?.Name}");
            }
            catch (AssertFailedException) { throw; }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, exception);
            }
        }
예제 #3
0
 public void ArgumentValidationDiagnosticFailing(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, Type exception)
 {
     try
     {
         // Act
         Container.RegisterType(typeFrom, typeTo, name, lifetimeManager);
         Assert.Fail("Did not throw and exception of type {exception?.Name}");
     }
     catch (Exception ex)
     {
         Assert.IsInstanceOfType(ex, exception);
     }
 }
예제 #4
0
 public IUnityContainer RegisterType(Type registeredType, Type mappedToType, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
 {
     throw new NotImplementedException();
 }
예제 #5
0
        /// <inheritdoc />
        IUnityContainer IUnityContainer.RegisterType(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
        {
            // Validate input
            var registeredType = ValidateType(typeFrom, typeTo);

            try
            {
                // Lifetime Manager
                var manager = lifetimeManager as LifetimeManager ?? Context.TypeLifetimeManager.CreateLifetimePolicy();
                if (manager.InUse)
                {
                    throw new InvalidOperationException(LifetimeManagerInUse);
                }
                manager.InUse = true;

                // Create registration and add to appropriate storage
                var container = manager is SingletonLifetimeManager ? _root : this;
                Debug.Assert(null != container);

                // If Disposable add to container's lifetime
                if (manager is IDisposable disposableManager)
                {
                    container.LifetimeContainer.Add(disposableManager);
                }

                // Add or replace existing
                var registration = new ExplicitRegistration(container, name, typeTo, manager, injectionMembers);
                var previous     = container.Register(registeredType, name, registration);

                // Allow reference adjustment and disposal
                if (null != previous && 0 == previous.Release() &&
                    previous.LifetimeManager is IDisposable disposable)
                {
                    // Dispose replaced lifetime manager
                    container.LifetimeContainer.Remove(disposable);
                    disposable.Dispose();
                }

                // Add Injection Members
                if (null != injectionMembers && injectionMembers.Length > 0)
                {
                    foreach (var member in injectionMembers)
                    {
                        member.AddPolicies <BuilderContext, ExplicitRegistration>(
                            registeredType, typeTo, name, ref registration);
                    }
                }

                // Check what strategies to run
                registration.Processors = Context.TypePipelineCache;

                // Raise event
                container.Registering?.Invoke(this, new RegisterEventArgs(registeredType,
                                                                          typeTo,
                                                                          name,
                                                                          manager));
            }
            catch (Exception ex)
            {
                var builder = new StringBuilder();

                builder.AppendLine(ex.Message);
                builder.AppendLine();

                var parts    = new List <string>();
                var generics = null == typeFrom ? typeTo?.Name : $"{typeFrom?.Name},{typeTo?.Name}";
                if (null != name)
                {
                    parts.Add($" '{name}'");
                }
                if (null != lifetimeManager && !(lifetimeManager is TransientLifetimeManager))
                {
                    parts.Add(lifetimeManager.ToString());
                }
                if (null != injectionMembers && 0 != injectionMembers.Length)
                {
                    parts.Add(string.Join(" ,", injectionMembers.Select(m => m.ToString())));
                }

                builder.AppendLine($"  Error in:  RegisterType<{generics}>({string.Join(", ", parts)})");
                throw new InvalidOperationException(builder.ToString(), ex);
            }

            return(this);
        }
예제 #6
0
        public void ArgumentValidationDiagnostic(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, Type manager)
        {
            // Act
            Container.RegisterType(typeFrom, typeTo, name, lifetimeManager);

            var registeredType = typeFrom ?? typeTo;
            var registration   = Container.Registrations.FirstOrDefault(r => r.RegisteredType == registeredType && r.Name == name);

            Assert.IsNotNull(registration);
            Assert.IsInstanceOfType(registration.LifetimeManager, manager);
        }
예제 #7
0
        /// <inheritdoc />
        IUnityContainer IUnityContainer.RegisterType(Type typeFrom, Type typeTo, string name, ITypeLifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
        {
            try
            {
                var mappedToType   = typeTo;
                var registeredType = typeFrom ?? typeTo;

                // Validate input
                if (null == typeTo)
                {
                    throw new ArgumentNullException(nameof(typeTo));
                }
                if (null == lifetimeManager)
                {
                    lifetimeManager = TransientLifetimeManager.Instance;
                }
                if (((LifetimeManager)lifetimeManager).InUse)
                {
                    throw new InvalidOperationException(LifetimeManagerInUse);
                }

                // Validate if they are assignable
                TypeValidator?.Invoke(typeFrom, typeTo);

                // Create registration and add to appropriate storage
                var container    = lifetimeManager is SingletonLifetimeManager ? _root : this;
                var registration = new ContainerRegistration(_validators, typeTo, (LifetimeManager)lifetimeManager, injectionMembers);

                // Add or replace existing
                var previous = container.Register(registeredType, name, registration);
                if (previous is ContainerRegistration old &&
                    old.LifetimeManager is IDisposable disposable)
                {
                    // Dispose replaced lifetime manager
                    container.LifetimeContainer.Remove(disposable);
                    disposable.Dispose();
                }

                // If Disposable add to container's lifetime
                if (lifetimeManager is IDisposable disposableManager)
                {
                    container.LifetimeContainer.Add(disposableManager);
                }

                // Add Injection Members
                if (null != injectionMembers && injectionMembers.Length > 0)
                {
                    foreach (var member in injectionMembers)
                    {
                        member.AddPolicies <BuilderContext, ContainerRegistration>(
                            registeredType, mappedToType, name, ref registration);
                    }
                }

                // Check what strategies to run
                registration.BuildChain = _strategiesChain.ToArray()
                                          .Where(strategy => strategy.RequiredToBuildType(this,
                                                                                          registeredType, registration, injectionMembers))
                                          .ToArray();
                // Raise event
                container.Registering?.Invoke(this, new RegisterEventArgs(registeredType,
                                                                          mappedToType,
                                                                          name,
                                                                          ((LifetimeManager)lifetimeManager)));
            }
            catch (Exception ex)
            {
                var parts    = new List <string>();
                var generics = null == typeFrom ? typeTo?.Name : $"{typeFrom?.Name},{typeTo?.Name}";
                if (null != name)
                {
                    parts.Add($" '{name}'");
                }
                if (null != lifetimeManager && !(lifetimeManager is TransientLifetimeManager))
                {
                    parts.Add(lifetimeManager.ToString());
                }
                if (null != injectionMembers && 0 != injectionMembers.Length)
                {
                    parts.Add(string.Join(" ,", injectionMembers.Select(m => m.ToString())));
                }

                var message = $"Error in  RegisterType<{generics}>({string.Join(", ", parts)})";
                throw new InvalidOperationException(message, ex);
            }

            return(this);
        }
예제 #8
0
        public static IUnityContainer RegisterLiteralService <TLiteralService>(this IUnityContainer container, ITypeLifetimeManager lifetimeManager)
            where TLiteralService : ILiteralService
        {
            container.RegisterType <ILiteralService, TLiteralService>(lifetimeManager);

            return(container);
        }
        public static IUnityContainer RegisterMediator(this IUnityContainer container, ITypeLifetimeManager lifetimeManager)
        {
            return(container.RegisterType <IMediator, Mediator>(lifetimeManager)
                   .RegisterInstance <ServiceFactory>(type =>
            {
                var enumerableType = type
                                     .GetInterfaces()
                                     .Concat(new[] { type })
                                     .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable <>));

                return enumerableType != null
                        ? container.ResolveAll(enumerableType.GetGenericArguments()[0])
                        : container.IsRegistered(type)
                            ? container.Resolve(type)
                            : null;
            }));
        }
        /// <summary>
        /// Register all the repositories services using the specified options builder.
        /// </summary>
        /// <param name="container">The unity container.</param>
        /// <param name="optionsAction">A builder action used to create or modify options for the repositories.</param>
        /// <param name="assembliesToScan">The assemblies to scan.</param>
        /// <param name="typelifetimeManager">The type lifetime manager for the service.</param>
        /// <param name="factorylifetimeManager">The factory lifetime manager for the service.</param>
        /// <remarks>
        /// This method will scan for repositories and interceptors from the specified assemblies collection, and will register them to the container.
        /// </remarks>
        public static void RegisterRepositories([NotNull] this IUnityContainer container, [NotNull] Action <RepositoryOptionsBuilder> optionsAction, [NotNull] Assembly[] assembliesToScan, ITypeLifetimeManager typelifetimeManager = null, IFactoryLifetimeManager factorylifetimeManager = null)
        {
            Guard.NotNull(container, nameof(container));
            Guard.NotNull(optionsAction, nameof(optionsAction));
            Guard.NotEmpty(assembliesToScan, nameof(assembliesToScan));

            var optionsBuilder = new RepositoryOptionsBuilder();

            optionsAction(optionsBuilder);

            var scanResults = AssemblyScanner.FindRepositoriesFromAssemblies(assembliesToScan);

            // Register scanned types
            scanResults.ForEach(scanResult =>
            {
                foreach (var implementationType in scanResult.ImplementationTypes)
                {
                    container.RegisterType(implementationType);

                    if (scanResult.InterfaceType == typeof(IRepositoryInterceptor))
                    {
                        container.RegisterType(scanResult.InterfaceType, implementationType, implementationType.FullName);
                    }
                    else
                    {
                        container.RegisterType(scanResult.InterfaceType, implementationType);
                    }
                }
            });

            // Register options services
            container.RegisterFactory <IRepositoryOptions>(c =>
            {
                var options = new RepositoryOptions(optionsBuilder.Options);

                foreach (var interceptorType in scanResults.OfType <IRepositoryInterceptor>())
                {
                    if (!options.Interceptors.ContainsKey(interceptorType))
                    {
                        options = options.With(interceptorType, () => (IRepositoryInterceptor)c.Resolve(interceptorType));
                    }
                }

                if (options.LoggerProvider == null)
                {
                    var loggerProviderType = scanResults.OfType <ILoggerProvider>().FirstOrDefault();

                    if (loggerProviderType != null)
                    {
                        options = options.With((ILoggerProvider)c.Resolve(loggerProviderType));
                    }
                }

                if (options.CachingProvider == null)
                {
                    var cacheProviderType = scanResults.OfType <ICacheProvider>().FirstOrDefault();

                    if (cacheProviderType != null)
                    {
                        options = options.With((ICacheProvider)c.Resolve(cacheProviderType));
                    }
                }

                return(options);
            }, factorylifetimeManager);

            // Register resolver
            RepositoryDependencyResolver.SetResolver(type => container.Resolve(type));

            container.RegisterFactory <IRepositoryDependencyResolver>(c => RepositoryDependencyResolver.Current, new ContainerControlledLifetimeManager());
        }
 /// <summary>
 /// Register all the repositories services using the specified options builder.
 /// </summary>
 /// <param name="container">The unity container.</param>
 /// <param name="optionsAction">A builder action used to create or modify options for the repositories.</param>
 /// <param name="typelifetimeManager">The type lifetime manager for the service.</param>
 /// <param name="factorylifetimeManager">The factory lifetime manager for the service.</param>
 /// <remarks>
 /// This method will scan for repositories and interceptors from the assemblies that have been loaded into the
 /// execution context of this application domain, and will register them to the container.
 /// </remarks>
 public static void RegisterRepositories([NotNull] this IUnityContainer container, [NotNull] Action <RepositoryOptionsBuilder> optionsAction, ITypeLifetimeManager typelifetimeManager = null, IFactoryLifetimeManager factorylifetimeManager = null)
 {
     RegisterRepositories(container, optionsAction, AppDomain.CurrentDomain.GetAssemblies(), typelifetimeManager);
 }
 /// <summary>
 /// Register all the repositories services using the specified options builder.
 /// </summary>
 /// <typeparam name="T">Used for scanning the assembly containing the specified type.</typeparam>
 /// <param name="container">The unity container.</param>
 /// <param name="optionsAction">A builder action used to create or modify options for the repositories.</param>
 /// <param name="typelifetimeManager">The type lifetime manager for the service.</param>
 /// <param name="factorylifetimeManager">The factory lifetime manager for the service.</param>
 /// <remarks>
 /// This method will scan for repositories and interceptors from the assemblies that have been loaded into the
 /// execution context of this application domain, and will register them to the container.
 /// </remarks>
 public static void RegisterRepositories <T>([NotNull] this IUnityContainer container, [NotNull] Action <RepositoryOptionsBuilder> optionsAction, ITypeLifetimeManager typelifetimeManager = null, IFactoryLifetimeManager factorylifetimeManager = null)
 {
     RegisterRepositories(container, optionsAction, new[] { typeof(T).GetTypeInfo().Assembly }, typelifetimeManager);
 }
        /// <summary>
        /// Register a <see cref="LifetimeManager"/> for the given type with the container.
        /// Map appsettings section into specified model (<see cref="T"/>).
        /// </summary>
        /// <typeparam name="T">The type to apply the <paramref name="lifetimeManager"/> to.</typeparam>
        /// <param name="container">Container to configure.</param>
        /// <param name="lifetimeManager">
        ///     This interface marks all lifetime managers compatible with
        /// <see cref="IUnityContainer.RegisterType" /> registration.
        /// <remarks>
        ///     This interface is used for design type validation of registration compatibility.
        ///     Each registration type only takes lifetime managers compatible with it.
        /// </remarks>
        /// </param>
        /// <returns>The <see cref="Unity.IUnityContainer"/> object that this method was called on.</returns>
        public static IUnityContainer RegisterAppSettings <T>(this IUnityContainer container, ITypeLifetimeManager lifetimeManager = null) where T : class
        {
            var settingType = typeof(T);

            List <InjectionMember> injectionMembers = new List <InjectionMember>();
            var appSettings = System.Configuration.ConfigurationManager.AppSettings;

            foreach (var settingPropertyInfo in settingType.GetProperties())
            {
                injectionMembers.Add(new InjectionProperty(
                                         settingPropertyInfo.Name,
                                         Convert.ChangeType(appSettings[settingPropertyInfo.Name],
                                                            Nullable.GetUnderlyingType(settingPropertyInfo.PropertyType) ?? settingPropertyInfo.PropertyType))
                                     );
            }

            if (injectionMembers != null && injectionMembers.Count > 0)
            {
                container.RegisterType <T>(lifetimeManager ?? new ContainerControlledLifetimeManager(), injectionMembers.ToArray());
            }

            return(container);
        }