Esempio n. 1
0
        public GenericHost(IConfigureThisEndpoint specifier, string[] args, List<Type> defaultProfiles, string endpointName, IEnumerable<string> scannableAssembliesFullName = null)
        {
            this.specifier = specifier;

            if (String.IsNullOrEmpty(endpointName))
            {
                endpointName = specifier.GetType().Namespace ?? specifier.GetType().Assembly.GetName().Name;
            }

            endpointNameToUse = endpointName;
            endpointVersionToUse = FileVersionRetriever.GetFileVersion(specifier.GetType());

            if (scannableAssembliesFullName == null || !scannableAssembliesFullName.Any())
            {
                var assemblyScanner = new AssemblyScanner();
                assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);
                assembliesToScan = assemblyScanner
                    .GetScannableAssemblies()
                    .Assemblies;
            }
            else
            {
                assembliesToScan = scannableAssembliesFullName
                    .Select(Assembly.Load)
                    .ToList();
            }

            profileManager = new ProfileManager(assembliesToScan, args, defaultProfiles);

            wcfManager = new WcfManager();
        }
Esempio n. 2
0
        public GraphBuilder(PluginGraph pluginGraph)
        {
            _pluginGraph = pluginGraph;
            _assemblyScanner = new AssemblyScanner();

            _instanceReader = new XmlInstanceReader(_pluginGraph.Log, new Registry());
        }
Esempio n. 3
0
 private static Type[] FindAllServiceTypes()
 {
     using (var scanner = new AssemblyScanner())
     {
         return scanner.GetConcreteTypesOf<IService>().ToArray();
     }
 }
        public void non_dotnet_files_are_skipped()
        {
            var assemblyScanner = new AssemblyScanner(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestDlls"));

            var results = assemblyScanner
                .GetScannableAssemblies();

            var skippedFiles = results.SkippedFiles;

            var notProperDotNetDlls = new[]
                {
                    "libzmq-v120-mt-3_2_3.dll",
                    "Tail.exe",
                    "some_random.dll",
                    "some_random.exe"
                };

            foreach (var notProperDll in notProperDotNetDlls)
            {
                var skippedFile = skippedFiles.FirstOrDefault(f => f.FilePath.Contains(notProperDll));

                if (skippedFile == null)
                {
                    throw new AssertionException($"Could not find skipped file matching {notProperDll}");
                }

                Assert.That(skippedFile.SkipReason, Contains.Substring("not a .NET assembly"));
            }
        }
Esempio n. 5
0
 private static void ResolveTypes()
 {
     var scanner = new AssemblyScanner();
     var foundType = scanner.FindTypes<IStartupTask>();
     startupTaskTypes.Clear();
     startupTaskTypes.AddRange(foundType);
 }
Esempio n. 6
0
        /// <summary>
        ///     Accepts the type which will specify the users custom configuration.
        ///     This type should implement <see cref="IConfigureThisEndpoint" />.
        /// </summary>
        /// <param name="scannableAssembliesFullName">Assemblies full name that were scanned.</param>
        /// <param name="specifier"></param>
        /// <param name="args"></param>
        /// <param name="defaultProfiles"></param>
        public GenericHost(IConfigureThisEndpoint specifier, string[] args, List<Type> defaultProfiles,
            IEnumerable<string> scannableAssembliesFullName = null)
        {
            this.specifier = specifier;

            endpointNameToUse = specifier.GetType().Namespace ?? specifier.GetType().Assembly.GetName().Name;

            if (scannableAssembliesFullName == null || !scannableAssembliesFullName.Any())
            {
                var assemblyScanner = new AssemblyScanner();
                assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);
                assembliesToScan = assemblyScanner
                    .GetScannableAssemblies()
                    .Assemblies;
            }
            else
            {
                assembliesToScan = scannableAssembliesFullName
                    .Select(Assembly.Load)
                    .ToList();
            }

            args = AddProfilesFromConfiguration(args);

            profileManager = new ProfileManager(assembliesToScan, args, defaultProfiles);
        }
Esempio n. 7
0
 private static IEnumerable<Type> GetMesageTypes(AssemblyScanner scanner)
 {
     return scanner.Types
                   .Where(Settings.IsCommandType)
                   .Union(scanner.Types.Where(Settings.IsEventType))
                   .Union(scanner.Types.Where(Settings.IsMessageType))
                   .Distinct();
 }
 private MockContext<IServiceContainer> GetContainerMock(Func<ILifetime> lifetimeFactory, Func<Type, Type, bool> shouldRegister)
 {
     var mockContext = new MockContext<IServiceContainer>();
     var containerMock = new ContainerMock(mockContext);            
     var assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), new CompositionRootTypeExtractor(), new CompositionRootExecutor(containerMock));
     assemblyScanner.Scan(typeof(IFoo).Assembly, containerMock, lifetimeFactory, shouldRegister);
     return mockContext;
 }
        public void Scan_SampleAssemblyWithCompositionRoot_CallsComposeMethodOnce()
        {
	        var containerMock = new ContainerMock(new MockContext<IServiceContainer>());
            var assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), new CompositionRootTypeExtractor(), new CompositionRootExecutor(containerMock));
            SampleCompositionRoot.CallCount = 0;
            assemblyScanner.Scan(typeof(SampleCompositionRoot).Assembly, containerMock);
            Assert.AreEqual(1, SampleCompositionRoot.CallCount);
        }
        public void Register_Assembly_RegistersConcreteTypeWithoutBaseclass()
        {
            var serviceRegistryMock = new Mock<IServiceRegistry>();
            AssemblyScanner assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), new CompositionRootTypeExtractor(), new CompositionRootExecutor(serviceRegistryMock.Object));
            assemblyScanner.Scan(typeof(IFoo).Assembly, serviceRegistryMock.Object, () => null, (s,t) => true);

            serviceRegistryMock.Verify(r => r.Register(typeof(ConcreteFoo), typeof(ConcreteFoo), "ConcreteFoo", null));
        }
Esempio n. 11
0
 public void ScanUsingPredicate_SampleAssemblyWithCompositionRoot_DoesNotCallCompositionRoot()
 {
     var containerMock = new ContainerMock(new MockContext<IServiceContainer>());
     var assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), new CompositionRootTypeExtractor(), new CompositionRootExecutor(containerMock));
     SampleCompositionRoot.CallCount = 0;
     assemblyScanner.Scan(typeof(SampleCompositionRoot).Assembly, containerMock,() => null, (s, t) => true);            
     Assert.AreEqual(0, SampleCompositionRoot.CallCount);
 }
        public void Should_have_scanner_context()
        {
            // Act
            var scanner = new AssemblyScanner();

            // Assert
            Assert.That(scanner.Context, Is.Not.Null);
            Assert.That(scanner.Context, Is.TypeOf<ScannerContext>());
        }
Esempio n. 13
0
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            var scanner = new AssemblyScanner();
            scanner.FromCallingAssembly();
            scanner.BindWith<DefaultBindingGenerator>();
            kernel.Scan(scanner);

            ProPartners.Loan.Service.Infrastructure.AppStart.RegisterAssemblies(kernel);
        }
Esempio n. 14
0
 public void Can_use_autoconfiguration()
 {
     var recognizes = new AssemblyScanner(this.GetType().Assembly).LooksLikeControllers().ToArray();
     Assert.That(recognizes, Is.EquivalentTo(new[] {
         typeof(MyController),
         typeof(ObjectController),
         typeof(DisposeController)
     }));
 }
Esempio n. 15
0
        public void Prime()
        {
            var scanner = new AssemblyScanner();
            var handlerTypes = scanner.FindTypes(typeof(IHandle<>));

            foreach (var handlerType in handlerTypes)
            {
                Add(handlerType);
            }
        }
        public void Should_skip_x64_assemblies()
        {
            var results = new AssemblyScanner()
                .GetScannableAssemblies();

            var x64SkippedDll = results.SkippedFiles.FirstOrDefault(s => s.FilePath.Contains("x64Assembly.dll"));

            Assert.That(x64SkippedDll, Is.Not.Null);
            Assert.That(x64SkippedDll.SkipReason, Contains.Substring("x64 .NET assembly can't be loaded by a 32Bit process"));
        }
 IEnumerable<Assembly> GetAssembliesInDirectory(string path, params string[] assembliesToSkip)
 {
     var assemblyScanner = new AssemblyScanner(path);
     if (assembliesToSkip != null)
     {
         assemblyScanner.AssembliesToSkip = assembliesToSkip.ToList();
     }
     return assemblyScanner
         .GetScannableAssemblies()
         .Assemblies;
 }
        public void Context()
        {
            var assemblyScanner = new AssemblyScanner(AssemblyLocation.CurrentDirectory)
                {
                    IncludeAppDomainAssemblies = false
                };
            assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);

            results = assemblyScanner
                .GetScannableAssemblies();
        }
        public static IKernel ScanAssemblies(IKernel kernel)
        {
            var scanner = new AssemblyScanner();
            scanner.FromAssembliesMatching("Basketball.Service.dll"); // Services classes here
            scanner.FromAssembliesMatching("Basketball.Data.dll");  // Repositories here
            scanner.BindWithDefaultConventions();

            kernel.Scan(scanner);

            return kernel;
        }
 public void Context()
 {
     var assemblyScanner = new AssemblyScanner(AssemblyLocation.CurrentDirectory)
         {
             AssembliesToInclude = new List<string>
                 {
                     "NServiceBus.Core.Tests.dll"
                 }
         };
     results = assemblyScanner
         .GetScannableAssemblies();
 }
        public void Should_scan_assemblies_from_application_base_directory_matching_predicate()
        {
            // Arrange
            var scanner = new AssemblyScanner();
            const int expectedAssembliesCount = 3;

            // Act
            scanner.AssembliesFromApplicationBaseDirectory(assembly => assembly.FullName.StartsWith("FluentSecurity."));

            // Assert
            Assert.That(scanner.Context.AssembliesToScan.Count(), Is.EqualTo(expectedAssembliesCount));
        }
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            var scanner = new AssemblyScanner();
            scanner.FromCallingAssembly();

            //This will register all interfaces with concrete types based on convention
            //ex: IPersonService will register to PersonService
            scanner.BindWith<DefaultBindingGenerator>();
            kernel.Scan(scanner);

            IMapperPOC.Service.Infrustructure.AppStart.RegisterAssemblies(kernel);
        }
Esempio n. 23
0
 private MockContext<IServiceContainer> GetContainerMock(Func<ILifetime> lifetimeFactory, Func<Type, Type, bool> shouldRegister)
 {            
     var containerMock = new ContainerMock();
     var compositionRootMock = new CompositionRootMock();     
     
     var compositionRootTypeExtractorMock = new TypeExtractorMock();
     compositionRootTypeExtractorMock.Arrange(c => c.Execute(The<Assembly>.IsAnyValue)).Returns(Type.EmptyTypes);
            
     var assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), compositionRootTypeExtractorMock, new CompositionRootExecutor(containerMock,t => compositionRootMock));
     assemblyScanner.Scan(typeof(IFoo).Assembly, containerMock, lifetimeFactory, shouldRegister);
     return containerMock;
 }
 public void UsingDefaultConventionsResolvesCorrectly()
 {
     using ( IKernel kernel = new StandardKernel() )
     {
         var scanner = new AssemblyScanner();
         scanner.Assembly( Assembly.GetExecutingAssembly() );
         scanner.UsingDefaultConventions();
         kernel.Scan( scanner );
         var instance = kernel.Get<IDefaultConvention>();
         Assert.NotNull( instance );
         Assert.Equal( typeof (DefaultConvention), instance.GetType() );
     }
 }
Esempio n. 25
0
        public static void ScanForEventListeners()
        {
            var assemblyScanner = new AssemblyScanner();
            assemblyScanner.AssembliesFromApplicationBaseDirectory();
            assemblyScanner.With(new SecurityEventListenerScanner(IgnoreTypeLoadExceptions));
            var eventListeners = assemblyScanner.Scan();

            foreach (var eventListenerType in eventListeners)
            {
                var eventListener = (ISecurityEventListener) Activator.CreateInstance(eventListenerType);
                Register(eventListener);
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="EndpointTypeDeterminer" /> class.
 /// </summary>
 /// <param name="assemblyScanner">The assembly scanner results.</param>
 /// <param name="getEndpointConfigurationTypeFromConfig">A func to retrieve the endpoint configuration type from config.</param>
 /// <exception cref="System.ArgumentNullException">assemblyScannerResults</exception>
 public EndpointTypeDeterminer(AssemblyScanner assemblyScanner,
     Func<string> getEndpointConfigurationTypeFromConfig)
 {
     if (assemblyScanner == null)
     {
         throw new ArgumentNullException("assemblyScanner");
     }
     if (getEndpointConfigurationTypeFromConfig == null)
     {
         throw new ArgumentNullException("getEndpointConfigurationTypeFromConfig");
     }
     this.assemblyScanner = assemblyScanner;
     this.getEndpointConfigurationTypeFromConfig = getEndpointConfigurationTypeFromConfig;
 }
Esempio n. 27
0
        static IEnumerable<Type> GetTypesToUse(EndpointConfiguration endpointConfiguration)
        {
            var assemblies = new AssemblyScanner().GetScannableAssemblies();

            var types = assemblies.Assemblies
                                    //exclude all test types by default
                                  .Where(a => a != Assembly.GetExecutingAssembly())
                                  .SelectMany(a => a.GetTypes());

            types = types.Union(GetNestedTypeRecursive(endpointConfiguration.BuilderType.DeclaringType, endpointConfiguration.BuilderType));

            types = types.Union(endpointConfiguration.TypesToInclude);

            return types.Where(t => !endpointConfiguration.TypesToExclude.Contains(t)).ToList();
        }
Esempio n. 28
0
        /// <summary>
        /// Returns an enumerator for looping over the assemblies to be loaded.
        /// </summary>
        public IEnumerator<Assembly> GetEnumerator()
        {
            var assemblyScanner = new AssemblyScanner(directory)
            {
                IncludeAppDomainAssemblies = true,
                AssembliesToInclude = assembliesToInclude,
                AssembliesToSkip = assembliesToExclude
            };
            assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);

            return assemblyScanner
                .GetScannableAssemblies()
                .Assemblies
                .GetEnumerator();
        }
Esempio n. 29
0
        public void Should_scan_assemblies_from_application_base_directory()
        {
            // Arrange
            var scanner                 = new AssemblyScanner();
            var extensionsToScan        = new[] { ".exe", ".dll" };
            var filesInBaseDirectory    = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory);
            var expectedAssembliesCount = filesInBaseDirectory.Count(file =>
            {
                var extension = Path.GetExtension(file);
                return(extensionsToScan.Contains(extension));
            });

            // Act
            scanner.AssembliesFromApplicationBaseDirectory();

            // Assert
            Assert.That(scanner.Context.AssembliesToScan.Count(), Is.EqualTo(expectedAssembliesCount));
        }
Esempio n. 30
0
        public void Configure(IServiceCollection services, IConfiguration configuration)
        {
            foreach (Assembly assembly in AssemblyScanner.GetAssemblies())
            {
                foreach (TypeInfo typeInfo in assembly.DefinedTypes)
                {
                    ConfigurationAttribute configurationAttribute = typeInfo.GetCustomAttribute <ConfigurationAttribute>();

                    if (configurationAttribute != null)
                    {
                        var instance = Activator.CreateInstance(typeInfo);
                        configuration.Bind(configurationAttribute.Section, instance);

                        services.AddSingleton(typeInfo, sp => instance);
                    }
                }
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Registration of CqrsVibe query handlers
        /// </summary>
        /// <param name="services">Service collection</param>
        /// <param name="lifetime">Lifetime</param>
        /// <param name="fromAssemblies">Assemblies containing handlers</param>
        /// <param name="warmUpHandlerInvokersCache">Warm up invokers cache of found handlers</param>
        public static IServiceCollection AddCqrsVibeQueryHandlers(
            this IServiceCollection services,
            ServiceLifetime lifetime,
            IEnumerable <Assembly> fromAssemblies,
            bool warmUpHandlerInvokersCache = true)
        {
            foreach (var handlerTypeDescriptor in AssemblyScanner.FindQueryHandlersFrom(
                         fromAssemblies,
                         warmUpHandlerInvokersCache))
            {
                services.Add(new ServiceDescriptor(
                                 handlerTypeDescriptor.HandlerType,
                                 handlerTypeDescriptor.ImplementationType,
                                 lifetime));
            }

            return(services);
        }
Esempio n. 32
0
        public void Does_not_throw_exception_when_scanning_duplicate_assemblies()
        {
            var busAssembly = new DynamicAssembly("Fake.NServiceBus.Core");

            Directory.CreateDirectory(Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir"));
            var destFileName = Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir", busAssembly.FileName);

            // create a duplicate of the scanned assembly in a subfolder:
            File.Copy(busAssembly.FilePath, destFileName);

            var scanner = new AssemblyScanner(DynamicAssembly.TestAssemblyDirectory)
            {
                ScanNestedDirectories = true,
                CoreAssemblyName      = busAssembly.DynamicName
            };

            Assert.DoesNotThrow(() => scanner.GetScannableAssemblies());
        }
Esempio n. 33
0
        private static void AddMediatr(IServiceCollection services)
        {
            const string applicationAssemblyName = "Anima.Student.Application.dll";

            AssemblyName an = AssemblyName.GetAssemblyName(GetPathApplication() + applicationAssemblyName);

            var assembly = System.Reflection.Assembly.Load(an);

            AssemblyScanner
            .FindValidatorsInAssembly(assembly)
            .ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(FailFastRequestBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(LoggingBehavior <,>));


            services.AddMediatR(assembly);
        }
        public void assemblies_without_nsb_reference_are_skipped()
        {
            var assemblyScanner = new AssemblyScanner(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestDlls"));

            var results = assemblyScanner
                          .GetScannableAssemblies();

            var skippedFiles = results.SkippedFiles;

            var skippedFile = skippedFiles.FirstOrDefault(f => f.FilePath.Contains("dotNet.dll"));

            if (skippedFile == null)
            {
                throw new AssertionException($"Could not find skipped file matching {"dotNet.dll"}");
            }
            Assert.That(skippedFile.SkipReason,
                        Contains.Substring("Assembly does not reference at least one of the must referenced assemblies"));
        }
Esempio n. 35
0
        public void No_files_explicitly_excluded_are_returned()
        {
            var results = new AssemblyScanner(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestDlls"))
            {
                AssembliesToSkip = new List <string>
                {
                    "dotNet.dll"
                },
                ScanAppDomainAssemblies = false
            }
            .GetScannableAssemblies();

            var skippedFiles         = results.SkippedFiles;
            var explicitlySkippedDll = skippedFiles.FirstOrDefault(s => s.FilePath.Contains("dotNet.dll"));

            Assert.That(explicitlySkippedDll, Is.Not.Null);
            Assert.That(explicitlySkippedDll.SkipReason, Contains.Substring("File was explicitly excluded from scanning"));
        }
Esempio n. 36
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCadastroData(Configuration.GetConnectionString("AppConnectionString"));
            services.AddCadastroQueries();
            services.AddCadastroServices();
            services.AddControllers();
            services.AddSwaggerGen(c => {
                c.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetEntryAssembly()?.GetName().Name}.xml"));
                c.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, $"{typeof(BusinessException).Assembly?.GetName().Name}.xml"));
            });
            services.AddMediatR(typeof(Startup), typeof(BusinessException));

            AssemblyScanner.FindValidatorsInAssembly(typeof(BusinessException).Assembly)
            .ForEach(item => services.AddScoped(item.InterfaceType, item.ValidatorType));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(PipelineValidationBehavior <,>));

            services.TryAddEnumerable(ServiceDescriptor.Transient <IApplicationModelProvider, ProduceResponseTypeModelProvider>());
        }
Esempio n. 37
0
        public void Assemblies_with_direct_reference_are_included()
        {
            var busAssembly           = new DynamicAssembly("Fake.NServiceBus.Core.dll");
            var assemblyWithReference = new DynamicAssembly("AssemblyWithReference.dll", new[]
            {
                busAssembly
            });

            var scanner = new AssemblyScanner(DynamicAssembly.TestAssemblyDirectory);

            scanner.CoreAssemblyName = busAssembly.DynamicName;

            var result = scanner.GetScannableAssemblies();

            Assert.IsTrue(result.Assemblies.Contains(assemblyWithReference));
            Assert.IsTrue(result.Assemblies.Contains(busAssembly));
            Assert.AreEqual(2, result.Assemblies.Count);
        }
        public static IEnumerable <Type> GetTypesScopedByTestClass(this EndpointCustomizationConfiguration endpointConfiguration)
        {
            var assemblies = new AssemblyScanner().GetScannableAssemblies();

            var assembliesToScan = assemblies.Assemblies
                                   //exclude acceptance tests by default
                                   .Where(a => a != Assembly.GetExecutingAssembly() && a != typeof(Bootstrapper).Assembly)
                                   .Where(a => a.FullName.StartsWith("ServiceControl") == false)
                                   .ToList();
            var types = assembliesToScan
                        .SelectMany(a => a.GetTypes());

            types = types.Union(GetNestedTypeRecursive(endpointConfiguration.BuilderType.DeclaringType, endpointConfiguration.BuilderType));

            types = types.Union(endpointConfiguration.TypesToInclude);

            return(types.Where(t => !endpointConfiguration.TypesToExclude.Contains(t)).ToList());
        }
Esempio n. 39
0
    private void LookForMethodCallers()
    {
        AssemblyScanner.Register(type => {
            var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            foreach (MethodInfo methodInfo in methods)
            {
                if (methodInfo.IsAbstract)
                {
                    continue;
                }
                MethodBody methodBody = methodInfo.GetMethodBody();
                if (methodBody == null)
                {
                    continue;
                }
                try{
                    List <Instruction> instructions = MethodBodyReader.GetInstructions(methodInfo);
                    foreach (var instruction in instructions)
                    {
                        MethodInfo calledMethod = instruction.Operand as MethodInfo;
                        if (calledMethod == null)
                        {
                            continue;
                        }
                        foreach (var users in allusers)
                        {
                            if (users.TryAddCall(type, methodInfo, calledMethod, instruction))
                            {
                                break;
                            }
                        }
                    }
                }catch (Exception e)
                {
                    //Debug.LogError("On " + methodInfo.DeclaringType.Name+"."+methodInfo.Name);
                    //Debug.LogException(e);
                }
            }
        },
                                 AssemblyScanner.OnlyProject
                                 );
        AssemblyScanner.Scan();
    }
        public void CanGetPluginFamilyFromPluginGraphWithNoParameters()
        {
            var builder = new PluginGraphBuilder();
            var scanner = new AssemblyScanner();

            scanner.Assembly(GetType().Assembly);

            builder.AddScanner(scanner);
            var graph = builder.Build();

            graph.Families[typeof(IGenericService <int>)].ShouldBeTheSameAs(
                graph.Families[typeof(IGenericService <int>)]);

            graph.Families[typeof(IGenericService <string>)].ShouldBeTheSameAs(
                graph.Families[typeof(IGenericService <string>)]);

            graph.Families[typeof(IGenericService <>)].ShouldBeTheSameAs(
                graph.Families[typeof(IGenericService <>)]);
        }
Esempio n. 41
0
        public IPolicyContainerConfiguration ForActionsMatching(Func <ControllerActionInfo, bool> actionFilter, params Assembly[] assemblies)
        {
            var assemblyScanner  = new AssemblyScanner();
            var assembliesToScan = assemblies.ToList();

            if (assembliesToScan.Any())
            {
                assemblyScanner.Assemblies(assemblies);
            }
            else
            {
                assemblyScanner.TheCallingAssembly();
            }

            assemblyScanner.With <ControllerTypeScanner>();
            var controllerTypes = assemblyScanner.Scan();

            return(CreateConventionPolicyContainerFor(controllerTypes, actionFilter));
        }
Esempio n. 42
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDatabaseConnection(Configuration.GetSection("Database:ConnectionString").Value);
     services.AddIdentityStores();
     services.AddCookieAuthentication();
     services.AddScoped <IMailSendingService, MailSendingService>();
     services.AddTransient <IFireAndForgetService, FireAndForgetService>();
     services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationBehavior <,>));
     AssemblyScanner.FindValidatorsInAssembly(typeof(AddRewardCommandValidator).Assembly)
     .ForEach(item => services.AddScoped(item.InterfaceType, item.ValidatorType));
     services.AddMediatR(typeof(GetUserRewardsQuery), typeof(ConfirmAccountCommand));
     services.AddControllers();
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("v1", new OpenApiInfo {
             Title = "Taskwind.API", Version = "v1"
         });
     });
 }
Esempio n. 43
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var forwardOptions = new ForwardedHeadersOptions
            {
                ForwardedHeaders      = ForwardedHeaders.All,
                RequireHeaderSymmetry = false
            };

            forwardOptions.KnownNetworks.Clear();
            forwardOptions.KnownProxies.Clear();

            app.UseForwardedHeaders(forwardOptions);

            List <IApplicationConfigurator> configurators = new List <IApplicationConfigurator>();

            foreach (Type type in AssemblyScanner.GetAllTypesOfInterface <IApplicationConfigurator>())
            {
                IApplicationConfigurator configurator = (IApplicationConfigurator)Activator.CreateInstance(type);
                configurators.Add(configurator);
            }

            foreach (IApplicationConfigurator configurator in configurators.OrderBy(c => c.Order))
            {
                configurator.Configure(app, env, SillycoreAppBuilder.Instance.Configuration, app.ApplicationServices);
            }

            app.UseMetricsAllMiddleware();
            app.UseMvc(r =>
            {
                if (SillycoreAppBuilder.Instance.DataStore.Get <bool>(Constants.RedirectRootToSwagger))
                {
                    r.MapRoute(name: "Default",
                               template: "",
                               defaults: new { controller = "Help", action = "Index" });
                }
                else
                {
                    r.MapRoute(name: "Default",
                               template: "",
                               defaults: new { controller = "Home", action = "Index" });
                }
            });
        }
Esempio n. 44
0
        public void dll_with_message_handlers_gets_loaded()
        {
            var assemblyScanner = new AssemblyScanner(AssemblyLocation.CurrentDirectory)
            {
                IncludeAppDomainAssemblies = false
            };

            var results = assemblyScanner
                          .GetScannableAssemblies();

            var containsHandlers = "NServiceBus.Core.Tests"; //< assembly name, not file name
            var assembly         = results.Assemblies
                                   .FirstOrDefault(a => a.GetName().Name.Contains(containsHandlers));

            if (assembly == null)
            {
                throw new AssertionException($"Could not find loaded assembly matching {containsHandlers}");
            }
        }
        public static void ConfigureMediatR(this IServiceCollection services, string projectName = "")
        {
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(MeasureTime <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(FailFastValidateCommand <,>));
            Assembly assembly;

            if (!string.IsNullOrEmpty(projectName) || !string.IsNullOrWhiteSpace(projectName))
            {
                assembly = Assembly.Load(projectName);
            }
            else
            {
                assembly = typeof(ICommand).GetTypeInfo().Assembly;
            }
            AssemblyScanner
            .FindValidatorsInAssembly(assembly)
            .ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));
            services.AddMediatR(assembly);
        }
Esempio n. 46
0
        public void Load()
        {
            var scanner = AssemblyScanner.Create(basePath);

            scanner.Scan();

            var assemblies = from assembly
                             in scanner.Assemblies
                             where (from type
                                    in assembly.TypeDefinitions
                                    where type.MatchesReflectionType(typeof(IRegistry))
                                    select type).Any()
                             select assembly;

            foreach (var assembly in assemblies)
            {
                Assembly.LoadFrom(assembly.FilePath);
            }
        }
        public static IServiceCollection AddApplication(this IServiceCollection services)
        {
            AssemblyScanner.FindValidatorsInAssemblies(new[] { Assembly.GetExecutingAssembly() })
            .ForEach(pair =>
            {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
                services.Add(ServiceDescriptor.Transient(pair.ValidatorType, pair.ValidatorType));
            });

            services.AddAutoMapper(new[] { Assembly.GetExecutingAssembly() });

            services.AddMediatR(new[] { Assembly.GetExecutingAssembly() });

            services.RegisterPipelineBehaviors();

            services.RegisterServices();

            return(services);
        }
        public void Throw_exception_on_assembly_loading_conflicts()
        {
            var busAssembly = new DynamicAssembly("Fake.NServiceBus.Core");

            Directory.CreateDirectory(Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir"));
            var destFileName = Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir", busAssembly.FileName);

            File.Copy(busAssembly.FilePath, destFileName);
            Assembly.LoadFrom(destFileName);

            var scanner = new AssemblyScanner(DynamicAssembly.TestAssemblyDirectory);

            scanner.ScanAppDomainAssemblies = true;
            scanner.CoreAssemblyName        = busAssembly.DynamicName;

            var exception = Assert.Throws <Exception>(() => scanner.GetScannableAssemblies());

            Assert.IsInstanceOf <FileLoadException>(exception.InnerException);
        }
        public void should_not_find_assembly_in_sub_directory()
        {
            var results = new AssemblyScanner(baseDirectoryToScan)
            {
                ScanAppDomainAssemblies = false,
                ScanNestedDirectories   = false
            }
            .GetScannableAssemblies();

            var allEncounteredFileNames =
                results.Assemblies
                .Where(x => !x.IsDynamic)
                .Select(a => a.CodeBase)
                .Concat(results.SkippedFiles.Select(s => s.FilePath))
                .ToList();

            Assert.That(allEncounteredFileNames.Any(f => f.Contains("NotAProper.dll")),
                        Is.False, "Did not expect to find NotAProper.dll among all encountered files because it resides in a sub directory");
        }
Esempio n. 50
0
        private static void RegisterFluentValidators(Container container, Assembly assembly)
        {
            var matches = AssemblyScanner.FindValidatorsInAssembly(assembly)
                          .Where(match => !match.ValidatorType.GetTypeInfo().IsInterface&&
                                 !match.ValidatorType.GetTypeInfo().IsAbstract);

            foreach (var match in matches)
            {
                var serviceType = match.ValidatorType.GetGenericType(typeof(IValidator <>));
                if (serviceType == null)
                {
                    continue;
                }

                var registration = Lifestyle.Singleton.CreateRegistration(match.ValidatorType, container);
                container.AddRegistration(match.ValidatorType, registration);
                container.AddRegistration(serviceType, registration);
            }
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin",
                                  options =>
                {
                    options.AllowAnyOrigin();
                });
            });

            var connectionString = Configuration["ConnectionStrings:sqlString"];

            services.AddDbContext <ConfitecDbContext>(opts => opts.UseSqlServer(connectionString), ServiceLifetime.Transient);

            services.AddScoped <IUsuarioRepository, UsuarioRepository>();

            services.AddControllers();

            services.AddMvc().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(FailFastRequestBehavior <,>));

            const string applicationAssemblyName = "Confitec.Application.dll";

            AssemblyName an = AssemblyName.GetAssemblyName(GetPathApplication() + applicationAssemblyName);

            var assembly = Assembly.Load(an);

            AssemblyScanner
            .FindValidatorsInAssembly(assembly)
            .ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(FailFastRequestBehavior <,>));

            services.AddMediatR(assembly);
        }
Esempio n. 52
0
        public void Should_not_include_child_type_if_only_handler_for_base_exists()
        {
            var messages =
                @"
public interface IBaseEvent
{
}

public interface IInheritedEvent : IBaseEvent
{
}
";

            var handler =
                @"
using NServiceBus;
using System.Threading.Tasks;

class InterfaceMessageHandler : IHandleMessages<IBaseEvent>
{
    public Task Handle(IBaseEvent message, IMessageHandlerContext context)
    {
        return Task.FromResult(0);
    }
}
";

            var messagesAsm = new DynamicAssembly("Fake.Messages", content: messages);

            Assembly.LoadFrom(messagesAsm.FilePath);

            var handlerAsm = new DynamicAssembly("Fake.Handler", new[] { messagesAsm }, content: handler, referenceTheCore: true);

            Assembly.LoadFrom(handlerAsm.FilePath);

            var scanner = new AssemblyScanner(DynamicAssembly.TestAssemblyDirectory);

            var result = scanner.GetScannableAssemblies();

            //Note this this is not the expected behavior. The assert will be changed to Assert.True and the test renamed as part of https://github.com/Particular/NServiceBus/issues/4634
            Assert.False(result.Types.Any(t => t.Name == "IInheritedEvent"));
        }
        public static IEnumerable <Type> GetTypesScopedByTestClass(this EndpointCustomizationConfiguration endpointConfiguration)
        {
            var assemblies = new AssemblyScanner().GetScannableAssemblies();

            var types = assemblies.Assemblies
                        //exclude all test types by default
                        .Where(a =>
            {
                var references = a.GetReferencedAssemblies();

                return(references.All(an => an.Name != "nunit.framework"));
            })
                        .SelectMany(a => a.GetTypes());

            types = types.Union(GetNestedTypeRecursive(endpointConfiguration.BuilderType.DeclaringType, endpointConfiguration.BuilderType));

            types = types.Union(endpointConfiguration.TypesToInclude);

            return(types.Where(t => !endpointConfiguration.TypesToExclude.Contains(t)).ToList());
        }
Esempio n. 54
0
        private static void AddMediatr(IServiceCollection services)
        {
            var assembly = AppDomain.CurrentDomain.Load("AccuScheduler.Application");

            // Validators.
            AssemblyScanner
            .FindValidatorsInAssembly(assembly)
            .ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));

            // Behaviors
            var behaviorType = typeof(IPipelineBehavior <,>);
            var behaviors    = assembly.DefinedTypes.Where(t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == behaviorType));

            foreach (var type in behaviors)
            {
                services.Add(new ServiceDescriptor(behaviorType, type, ServiceLifetime.Scoped));
            }

            services.AddMediatR(assembly);
        }
Esempio n. 55
0
        public void Ignore_assembly_loading_errors_when_disabling_ThrowExceptions()
        {
            var busAssembly = new DynamicAssembly("Fake.NServiceBus.Core");

            Directory.CreateDirectory(Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir"));
            var destFileName = Path.Combine(DynamicAssembly.TestAssemblyDirectory, "subdir", busAssembly.FileName);

            File.Copy(busAssembly.FilePath, destFileName);
            Assembly.LoadFrom(destFileName);

            var scanner = new AssemblyScanner(DynamicAssembly.TestAssemblyDirectory);

            scanner.ScanAppDomainAssemblies = true;
            scanner.CoreAssemblyName        = busAssembly.DynamicName;
            scanner.ThrowExceptions         = false;

            var result = scanner.GetScannableAssemblies();

            Assert.IsTrue(result.Assemblies.Contains(busAssembly));
        }
Esempio n. 56
0
        public void should_not_contains_private_classes_when_nonpublictypes_is_not_included()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------

            // None.

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            FromAssemblyDefiner instance = AssemblyScanner.FromAssemblyInThisApplicationDirectory();

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            instance.ExcludeAssemblyContaining <IAdditionalAssemblyService>()
            .GetAllTypes()
            .Should().NotContain(typeof(SomePrivateClass));
        }
Esempio n. 57
0
        public void TestDummyAssemblyContainsSomeAssemblyReferences()
        {
            var testDir = TestContext.CurrentContext.TestDirectory;

            var scanner = AssemblyScanner.Create(testDir + "/Assets");

            scanner.Scan();

            var assemblies = scanner.Assemblies;

            var core = from assembly
                       in assemblies
                       where assembly.Name == "CleanIoc.Core"
                       select assembly;

            var references = core.FirstOrDefault().AssemblyReferences;

            Assert.That(references, Is.Not.Null);
            Assert.That(references, Is.Not.Empty);
        }
Esempio n. 58
0
        public void TestScannerFindsTheDummyAssembly()
        {
            var testDir = TestContext.CurrentContext.TestDirectory;

            var scanner = AssemblyScanner.Create(testDir + "/Assets");

            scanner.Scan();

            var assemblies = scanner.Assemblies;

            Assert.That(assemblies, Is.Not.Null);
            Assert.That(assemblies, Has.Count.EqualTo(4));

            var core = from assembly
                       in assemblies
                       where assembly.Name == "CleanIoc.Core"
                       select assembly;

            Assert.That(core.FirstOrDefault(), Is.Not.Null);
        }
Esempio n. 59
-1
 private static void ResolveTypes()
 {
     var scanner = new AssemblyScanner();
     var foundType = scanner.FindTypes<IMessageFilter>();
     filterTypes.Clear();
     filterTypes.AddRange(foundType);
 }
        public void AssertAllActionsAreConfigured(Assembly[] assemblies)
        {
            var assemblyScanner = new AssemblyScanner();
            assemblyScanner.Assemblies(assemblies);
            assemblyScanner.With<ControllerTypeScanner>();

            var controllerTypes = assemblyScanner.Scan();

            var unconfiguredActions = (
                from c in controllerTypes
                from a in c.GetActionMethods()
                let actionName = a.GetActionName()
                let controllerName = c.GetControllerName()
                where PolicyContainers.GetContainerFor(controllerName, actionName) == null
                select new { ControllerName = controllerName, ActionName = actionName }
                ).ToList();

            if (unconfiguredActions.Any())
            {
                var errorMessageBuilder = new StringBuilder();
                unconfiguredActions.Each(a =>
                    errorMessageBuilder.AppendLine("- Security has not been configured for {0} action {1}.".FormatWith(a.ControllerName, a.ActionName))
                );
                throw new ConfigurationErrorsException(errorMessageBuilder.ToString());
            }
        }