Пример #1
0
        /// <summary>
        ///     Create an Inyector Mode from a AspNetCore ServiceLifetime
        /// </summary>
        /// <param name="lifetime">lifetime to create the mode</param>
        /// <param name="services">Asp.Net Core Service inyection</param>
        /// <returns>An Instance of Inyector Mode</returns>
        public static Mode Create(ServiceLifetime lifetime, IServiceCollection services)
        {
            switch (lifetime)
            {
            case ServiceLifetime.Scoped:
                return(new Mode
                {
                    InyectorMethod =
                        (type, inter) => services.AddScoped(inter, type),
                    Name = lifetime.ToString()
                });

            case ServiceLifetime.Singleton:
                return(new Mode
                {
                    InyectorMethod =
                        (type, inter) => services.AddSingleton(inter, type),
                    Name = lifetime.ToString()
                });

            case ServiceLifetime.Transient:
                return(new Mode
                {
                    InyectorMethod =
                        (type, inter) => services.AddTransient(inter, type),
                    Name = lifetime.ToString()
                });

            default:
                throw new ArgumentOutOfRangeException(nameof(lifetime), lifetime, null);
            }
        }
Пример #2
0
        public AndConstraint <ServiceCollectionAssertions> BeRegistered(Type serviceType, Type implementationType, ServiceLifetime lifetime, string because = "", params object[] becauseArgs)
        {
            AssertionScope scope = Execute.Assertion;

            scope.AddReportable("lifetime", lifetime.ToString().ToLowerInvariant());
            scope
            .BecauseOf(because, becauseArgs)
            .WithExpectation("Expected {context:service collection} to contain a {lifetime} registration for {0} implemented by {1}{reason}, ", serviceType, implementationType)
            // Match service and lifetime
            .Given(() => Subject.Where(d => d.ServiceType == serviceType))
            .ForCondition(reg => reg.Any())
            .FailWith("but the service was not found.")
            .Then
            .ForCondition(reg => reg.Any(d => d.Lifetime == lifetime))
            .FailWith("but found {0}.", reg => reg.Select(d => d.Lifetime).Distinct())
            .Then
            .Given(reg => reg.FirstOrDefault(d => d.Lifetime == lifetime))
            .ForCondition(r =>
                          // Match implementation, instance or factory
                          r.ImplementationType == implementationType ||
                          r.ImplementationInstance != null && implementationType.IsInstanceOfType(r.ImplementationInstance) ||
                          r.ImplementationFactory != null
                          )
            .FailWith("but it does not.")
            ;

            return(new AndConstraint <ServiceCollectionAssertions>(this));
        }
        public ICallistoCollectionConfigurator ConfigureCollection <TInterface, TConcrete,
                                                                    TDocumentRoot>(string database,
                                                                                   string collection,
                                                                                   ServiceLifetime lifetime,
                                                                                   Func <IServiceProvider, object[]> extraDependencies = null)
            where TDocumentRoot : class, IDocumentRoot
            where TConcrete : CallistoCollection <TDocumentRoot>, TInterface

        {
            ConfigureCollectionContext <TDocumentRoot>(database, collection, lifetime);
            _solariBuilder.Services.Add(ServiceDescriptor.Describe(typeof(TInterface), provider =>
            {
                CallistoLogger.CollectionLogger.Registering(collection, lifetime.ToString());
                var context = provider.GetRequiredService <ICallistoCollectionContext <TDocumentRoot> >();
                CollectionOperators <TDocumentRoot> operators = CreateCollectionOperators <TInterface, TConcrete, TDocumentRoot>(context.Collection, provider);
                if (extraDependencies is null)
                {
                    return(ActivatorUtilities.CreateInstance <TConcrete>(provider, context, operators));
                }
                object[] extra = extraDependencies(provider);

                return(ActivatorUtilities.CreateInstance <TConcrete>(provider, context, operators, extra));
            }, lifetime));

            return(this);
        }
Пример #4
0
        /// <summary>
        ///     Apply a Naming convention rule with an Assembly
        ///     example : ICarRepository match with CarRepository
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="assembly">Assembly to apply rule</param>
        /// <param name="lifetime">AspNet Core mode to inyect </param>
        /// <returns>a instance of IInyectorConfiguration</returns>
        public static InyectorConfiguration AddRuleForNamingConvention(this InyectorConfiguration configuration,
                                                                       Assembly assembly,
                                                                       ServiceLifetime lifetime)
        {
            configuration.AddRule(assembly, (t1, t2) => $"I{t1.Name}" == t2.Name, lifetime.ToString());

            return(configuration);
        }
Пример #5
0
        /// <summary>
        ///     Add Rule from LifeTime using the default models and a target Assembly
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="assembly">Assembly to apply the rule</param>
        /// <param name="criteria">Criteria to find the types</param>
        /// <param name="lifetime">lifetime</param>
        /// <returns></returns>
        public static InyectorConfiguration AddRule(this InyectorConfiguration configuration,
                                                    Assembly assembly,
                                                    Func <Type, Type, bool> criteria,
                                                    ServiceLifetime lifetime)
        {
            configuration.AddRule(assembly, criteria, lifetime.ToString());

            return(configuration);
        }
Пример #6
0
        /// <summary>
        ///     Apply a Naming convention rule with an assembly
        ///     with ends with names example only inyect classes that finish with [Repository, Helper, Services, Factory, and so
        ///     on...]
        ///     example : ICarRepository match with CarRepository
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="assembly">Assembly to apply rule</param>
        /// <param name="names">names to find is the type name finish with</param>
        /// <param name="lifetime">AspNet Core mode to inyect </param>
        /// <returns>a instance of IInyectorConfiguration</returns>
        public static InyectorConfiguration AddRuleForEndsWithNamingConvention(this InyectorConfiguration configuration,
                                                                               Assembly assembly,
                                                                               IEnumerable <string> names,
                                                                               ServiceLifetime lifetime)
        {
            configuration.AddRule(assembly, (t1, t2) => names.Any(n => t1.Name.ToLower().EndsWith(n.ToLower())) &&
                                  $"I{t1.Name}" == t2.Name,
                                  lifetime.ToString());

            return(configuration);
        }
        private static LifetimeManager GetLifetimeManager(ServiceLifetime lifecycle)
        {
            switch (lifecycle)
            {
            case ServiceLifetime.Singleton:
                return(new ContainerControlledLifetimeManager());

            case ServiceLifetime.Scoped:
                return(new HierarchicalLifetimeManager());

            case ServiceLifetime.Transient:
                return(new TransientLifetimeManager());

            default:
                throw new NotSupportedException(lifecycle.ToString());
            }
        }
        /// <summary>
        /// Add all classes which inherits or implements the base type from the specific assembly.
        /// </summary>
        /// <param name="services">Service collection.</param>
        /// <param name="baseType">Base type.</param>
        /// <param name="assembly"><see cref="Assembly"/> in which to search.</param>
        /// <param name="serviceLifetime"><see cref="ServiceLifetime"/> with which the founded classes to be added.</param>
        /// <returns>Returns <see cref="IServiceCollection"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when services, baseType or assembly is null.</exception>
        /// <exception cref="ArgumentException">Thrown when serviceLifeTime is different from <see cref="ServiceLifetime.Transient"/>, <see cref="ServiceLifetime.Scoped"/> or <see cref="ServiceLifetime.Singleton"/>.</exception>
        /// <example>
        /// This is an example, showing how to use <see cref="AddAll(IServiceCollection, Type, Assembly, ServiceLifetime)"/>.
        /// <code>
        /// services.AddAll(typeof(IDbService), Assembly.GetAssembly(typeof(IDbService)), ServiceLifeTime.Scoped);
        /// </code>
        /// </example>
        public static IServiceCollection AddAll(this IServiceCollection services, Type baseType, Assembly assembly, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services), "Services cannot be null.");
            }

            if (baseType == null)
            {
                throw new ArgumentNullException(nameof(baseType), "Base type cannot be null.");
            }

            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly), "Assembly cannot be null.");
            }

            assembly.GetExportedTypes()
            .ForEach(t =>
            {
                if (!t.IsAbstract &&
                    ((baseType.IsInterface && t.ImplementsInterface(baseType)) ||
                     (!baseType.IsInterface && baseType.IsAssignableFrom(t))))
                {
                    switch (serviceLifetime)
                    {
                    case ServiceLifetime.Singleton:
                        services.AddSingleton(t);
                        break;

                    case ServiceLifetime.Scoped:
                        services.AddScoped(t);
                        break;

                    case ServiceLifetime.Transient:
                        services.AddTransient(t);
                        break;

                    default:
                        throw new ArgumentException($"Unsupported ServiceLifeTime enum value: {serviceLifetime.ToString()}.", nameof(serviceLifetime));
                    }
                }
            });

            return(services);
        }