Exemple #1
0
        public override void Init()
        {
            base.Init();

            var mockBufferSize = MockRepository.GenerateStub <IBufferSize>();

            mockBufferSize.Stub(x => x.Value).Return(1000);
            ObjectFactory.Configure(x => x.For <IBufferSize>().HybridHttpOrThreadLocalScoped().Use(mockBufferSize));

            ObjectFactory.GetInstance <TransportMock>().On <AddAttachmentPartToMessageCommand>()
            .Reply(x =>
            {
                if (!x.IsLastPart)
                {
                    return(new AttachmentPartAddedMessage {
                        FileName = x.FileName
                    });
                }
                return(new AttachmentCreatedMessage
                {
                    Dto = new AttachmentDTO
                    {
                        OriginalFileName = x.FileName,
                        GeneralID = x.GeneralId,
                        CreateDate = x.CreateDate,
                        OwnerID = x.OwnerId,
                        Description = x.Description
                    }
                });
            });
        }
 public void Init()
 {
     ObjectFactory.Initialize(x => x.AddRegistry <VcsMockEnvironmentRegistry>());
     ObjectFactory.Configure(x => x.For <TransportMock>().Use(TransportMock.CreateWithoutStructureMapClear(typeof(SubversionPluginProfile).Assembly, new List <Assembly> {
         typeof(Command).Assembly
     })));
 }
Exemple #3
0
        public void Start()
        {
            ObjectFactory.Configure(x =>
            {
                x.Scan(p =>
                {
                    p.AssembliesFromApplicationBaseDirectory();
                    p.AddAllTypesOf <IHttpHandler>().NameBy(q =>
                    {
                        var att = q.GetCustomAttributes(typeof(HttpCodeAttribute), true).FirstOrDefault();
                        return((att as HttpCodeAttribute).Code.ToLower());
                    });
                });
            });

            Action <HttpListener> act = p =>
            {
                p.Start();
                //Logger.WriteLog(LogType.INFO, "http服务器监听开启");
                status = true;
                while (status)
                {
                    var httpContext = p.GetContext();
                    ThreadPool.QueueUserWorkItem(Process, httpContext);
                }
            };

            act.BeginInvoke(listener, null, null);
        }
        public void Configuration(IAppBuilder app)
        {
            var container = ObjectFactory.Container;
            var resolver  = new StructureMapSignalRDependencyResolver(container);

            ObjectFactory.Configure(x =>
            {
                x.For <Microsoft.AspNet.SignalR.StockTicker.IStockTicker>()
                .Singleton()
                .Use <Microsoft.AspNet.SignalR.StockTicker.StockTicker>();

                x.For <IHubConnectionContext>().ConditionallyUse(c =>
                                                                 c.If(t => t.ParentType.GetInterface(typeof(Microsoft.AspNet.SignalR.StockTicker.IStockTicker).Name) ==
                                                                      typeof(Microsoft.AspNet.SignalR.StockTicker.IStockTicker))
                                                                 .ThenIt.Is.ConstructedBy(
                                                                     () => resolver.Resolve <IConnectionManager>().GetHubContext <StockTickerHub>().Clients)
                                                                 );
            });

            var config = new HubConfiguration()
            {
                Resolver = resolver
            };

            //Set GlobalHost dependency resolver to ensure hubs utilize the same configuration (http://jerodkrone.com/signalr-2-0-dependency-injection-using-globalhost/).
            GlobalHost.DependencyResolver = resolver;

            //Required For iPad, without this the "Spinner" will spin infinitely (https://github.com/SignalR/SignalR/issues/1406).
            GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(1);
            GlobalHost.Configuration.LongPollDelay     = TimeSpan.FromSeconds(5);

            Microsoft.AspNet.SignalR.StockTicker.Startup.ConfigureSignalR(app, config);
        }
        public void Configure()
        {
            ObjectFactory.Configure(x =>
            {
                x.Scan(scan =>
                {
                    scan.WithDefaultConventions();
                    scan.ConnectImplementationsToTypesClosing(typeof(IRepository <>));
                    scan.ConnectImplementationsToTypesClosing(typeof(IGetObjectService <>));
                    scan.ConnectImplementationsToTypesClosing(typeof(ISaveObjectService <>));
                    scan.ConnectImplementationsToTypesClosing(typeof(IDeleteObjectService <>));
                    scan.AssemblyContainingType(typeof(StructureMapConfiguration));

                    foreach (var assembly in _assembliesToScan)
                    {
                        scan.Assembly(assembly);
                    }
                });

                x.For <IDataContext>()
                .LifecycleIs(new HybridLifecycle())
                .Use(c =>
                     new DataContext(ConfigurationManager.ConnectionStrings["MainDatabase"].ConnectionString));
                x.For(typeof(IRepository <>)).Use(typeof(Repository <>));
                x.For(typeof(IGetObjectService <>)).Use(typeof(GetObjectService <>));
                x.For(typeof(ISaveObjectService <>)).Use(typeof(SaveObjectService <>));
                x.For(typeof(IDeleteObjectService <>)).Use(typeof(DeleteObjectService <>));

                ConfigureHttpInterfaces(x);
            });
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(ObjectFactory.Container));
        }
        /// <summary>
        /// Initializes the structure map.
        /// </summary>
        /// <returns></returns>
        public static void ConfigureStructureMap()
        {
            ObjectFactory.Configure(x =>
            {
                x.For <IVirtualPathResolver>().Use <VirtualPathResolver>();

                x.For <IPathResolver>().Use <PathResolver>();

                x.For <IPathData>().Use <PathData>();

                x.For <IControllerMapper>().Use <ControllerMapper>();

                x.Scan(scanner =>
                {
                    scanner.AssembliesFromApplicationBaseDirectory();
                    scanner.ExcludeNamespace("System");
                    scanner.ExcludeNamespace("Microsoft");
                    scanner.ExcludeNamespace("WebActivatorEx");
                    scanner.ExcludeNamespace("Newtonsoft");
                    scanner.ExcludeNamespace("Raven");
                    scanner.WithDefaultConventions();
                    scanner.Convention <ContentTypeRegistrationConvetion>();
                });

                x.For <IPage>().UseSpecial(y => y.ConstructedBy(r => ((MvcHandler)HttpContext.Current.Handler).RequestContext.RouteData.GetCurrentPage <IPage>()));

                x.For <IStructureInfo>().UseSpecial(y => y.ConstructedBy(r => ((MvcHandler)HttpContext.Current.Handler).RequestContext.RouteData.GetStructureInfo()));
            });
        }
        private static InversionContainer build_items_for_container(ConfigurationPropertyHolder configuration_property_holder)
        {
            configuration_property_holder.DatabaseType = DatabaseTypeSynonyms.convert_database_type_synonyms(configuration_property_holder.DatabaseType);

            set_up_current_mappings(configuration_property_holder);

            Logger multiLogger = GetMultiLogger(configuration_property_holder);

            ObjectFactory.Configure(cfg =>
            {
                cfg.For <ConfigurationPropertyHolder>().Singleton().Use(configuration_property_holder);
                cfg.For <FileSystemAccess>().Singleton().Use <WindowsFileSystemAccess>();
                cfg.For <Database>().Singleton().Use(context => DatabaseBuilder.build(context.GetInstance <FileSystemAccess>(), configuration_property_holder));
                cfg.For <KnownFolders>().Singleton().Use(context => KnownFoldersBuilder.build(context.GetInstance <FileSystemAccess>(), configuration_property_holder));
                cfg.For <LogFactory>().Singleton().Use <MultipleLoggerLogFactory>();
                //cfg.For<Logger>().Singleton().Use(context => LogBuilder.build(context.GetInstance<FileSystemAccess>(), configuration_property_holder));
                cfg.For <Logger>().Use(multiLogger);
                cfg.For <CryptographicService>().Singleton().Use <MD5CryptographicService>();
                cfg.For <DatabaseMigrator>().Singleton().Use(context => new DefaultDatabaseMigrator(context.GetInstance <Database>(), context.GetInstance <CryptographicService>(), configuration_property_holder));
                cfg.For <VersionResolver>().Singleton().Use(
                    context => VersionResolverBuilder.build(context.GetInstance <FileSystemAccess>(), configuration_property_holder));
                cfg.For <Environment>().Singleton().Use(new DefaultEnvironment(configuration_property_holder));
            });

            // forcing a build of database to initialize connections so we can be sure server/database have values
            Database database = ObjectFactory.GetInstance <Database>();

            database.initialize_connections(configuration_property_holder);
            configuration_property_holder.ServerName       = database.server_name;
            configuration_property_holder.DatabaseName     = database.database_name;
            configuration_property_holder.ConnectionString = database.connection_string;

            return(new StructureMapContainer(ObjectFactory.Container));
        }
        public void RegisterType(Type type)
        {
            var life = ParseLife(type);

            if (!IsRegistered(type))
            {
                if (life == LifeStyle.Singleton)
                {
                    ObjectFactory.Configure(x => x.For(type).Singleton().Use(type));
                }
                else
                {
                    ObjectFactory.Configure(x => x.For(type).Use(type));
                }
            }

            foreach (var interfaceType in type.GetInterfaces())
            {
                if (!IsRegistered(interfaceType))
                {
                    if (life == LifeStyle.Singleton)
                    {
                        ObjectFactory.Configure(x => x.For(interfaceType).Singleton().Use(type));
                    }
                    else
                    {
                        ObjectFactory.Configure(x => x.For(interfaceType).Use(type));
                    }
                }
            }
        }
Exemple #9
0
        public void SetUp()
        {
            StructureMapBootstrapper.Execute();
            ObjectFactory.Configure(x => x.For <IServiceBus>().Use <FakeServiceBus>());

            _sut = new EdiDocsInService();
        }
Exemple #10
0
        public static void Setup()
        {
            ObjectFactory.Configure(c =>
            {
                c.For <ISmtpClient>().Use <DotNetBuiltInSmtpClient>();
                c.For <IRepository <EmailQueueItem> >().Singleton().Use(() => new DbSetRepository <EmailQueueItem>(new EmailQueueDbContext()));
                var config = TroutConfiguration.GetMailMessageSenderConfig();
                c.For <IMailMessageSenderConfig>().Use(config);
                c.For <IMailMessageSenderConfig>().Use(config);
                c.For <IFileSystemAttachmentHandlerConfig>().Use(config);
                c.For <IAttachmentFileSystem>().Use <AttachmentFileSystem>();
                c.For <IStaticOverridesProvider>().Use <ConfigFileStaticOverridesProvider>();
                c.ForConcreteType <MailMessageQueue>();
                c.ForConcreteType <MailMessageDequeuer>();
                c.ForConcreteType <AddCommand>();
                c.ForConcreteType <ExitCommand>();
                c.ForConcreteType <HelpCommand>();
                c.ForConcreteType <ListCommand>();
                c.ForConcreteType <SendCommand>();
                c.ForConcreteType <EditCommand>();
                c.ForConcreteType <AttachmentsCommand>();
            }


                                    );

            DependencyResolver.SetDependencyResolver(new StructureMapDependencyResolver(ObjectFactory.Container));
        }
Exemple #11
0
        /// <summary>
        /// Creates the and configure application di container.
        /// </summary>
        /// <returns>A StructureMap Container.</returns>
        protected virtual IContainer CreateAndConfigureApplicationDiContainer()
        {
            ObjectFactory.Configure(
                x => x.Scan(
                    scanner =>
            {
                // In the scan operation, include all needed dlls as defined in the helper class.
                // be cautious in the future - this could still pick up unwanted assemblies,
                // such as the stray test project that mistakenly ends up in the bin folder.
                // so consider those possibilities if errors pop up, and you're led here.
                // scanner.AssembliesFromApplicationBaseDirectory(AutoRegistrationAssemblyHelper.ShouldStructureMapIncludeAssembly);
                scanner.AssembliesFromApplicationBaseDirectory(AutoRegistrationAssemblyHelper.ShouldStructureMapIncludeAssembly);

                scanner.LookForRegistries();

                // Register all boostrapper tasks
                scanner.AddAllTypesOf <IBootstrapperTask> ();

                // Register All Permission Descriptors
                scanner.AddAllTypesOf <IPermissionDescriptor> ();

                scanner.AddAllTypesOf <IAsyncRequestProcessor> ();

                scanner.WithDefaultConventions();
            }));

            return(ObjectFactory.Container);
        }
Exemple #12
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer(new MigrateDatabaseToLatestVersion <ApplicationDbContext, DefaultMigrationConfiguration>());

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => this.Container ?? ObjectFactory.Container));

            ObjectFactory.Configure(cfg =>
            {
                cfg.AddRegistry(new StandardRegistry());
                cfg.AddRegistry(new ControllerRegistry());
                cfg.AddRegistry(new ActionFilterRegistry(() => Container ?? ObjectFactory.Container));
                cfg.AddRegistry(new MvcRegistry());
                //// TODO: cfg.AddRegistry(new TaskRegistry());
                cfg.AddRegistry(new DataRegistry());
            });

            var autoMapperConfig = new AutoMapperConfig();

            autoMapperConfig.Execute();
        }
Exemple #13
0
        private static void Configure()
        {
            var config = new FoundationConfigurator
            {
                Business =
                {
                    BusinessInvocationLogger =
                        typeof(Kafala.BusinessManagers.SqlProcBusinessManagerInvocationLogger),
                    EmailLogger              = typeof(Foundation.Infrastructure.Notifications.EmailLogger)
                },

                Persistence =
                {
                    PocoPointer             = typeof(Kafala.Entities.Donor),
                    ConnectionStringKeyName = "Kafaladb"
                },

                UseBuseinssManagers = true,
                UseEmailing         = false,
                UsePresistence      = true,
                UseQueryContainer   = false,
                UseSecurity         = false,
                UseWeb = false,
            };

            FoundationKickStart.Configure(config);

            ObjectFactory.Configure(cfg => new Foundation.Persistence.Configurations.PersistenceConfigurator().Configure(cfg, config));

            ObjectFactory.Configure(cfg => new Foundation.Infrastructure.Configurations.InfrastructureConfigurator().Configure(cfg, config));
        }
Exemple #14
0
        private static void Main(string[] args)
        {
            BootstrapLogger();

            MsmqEndpointConfigurator.Defaults(x => { x.CreateMissingQueues = true; });

            HostFactory.Run(config =>
            {
                config.SetServiceName(typeof(Program).Namespace);
                config.SetDisplayName(typeof(Program).Namespace);
                config.SetDescription(typeof(Program).Namespace);

                config.RunAsLocalSystem();

                config.DependsOnMsmq();
                config.DependsOnMsSql();


                ObjectFactory.Configure(x =>
                {
                    x.AddRegistry(new GatewayServiceRegistry());
                });

                config.Service <OrderServiceGateway>(service =>
                {
                    service.ConstructUsing(() => ObjectFactory.GetInstance <OrderServiceGateway>());
                    service.WhenStarted(x => x.Start());
                    service.WhenStopped(x => x.Stop());
                });

                config.AfterStoppingServices(x => { _log.Info("Exiting..."); });
            });
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="StructureMapServiceHostFactory" /> class.
 /// </summary>
 public StructureMapServiceHostFactory()
 {
     ObjectFactory.Configure(x => x.Scan(scan =>
     {
         scan.TheCallingAssembly();
         scan.WithDefaultConventions();
     }));
     ObjectFactory.Initialize(x =>
     {
         //x.For<Logic.Services.IOrderService>().Use<Application.Services.OrderService>();
         //x.For<IOrderRepository>().Use<OrderRepository>();
         x.For <IMenuRepository>().Use <MenuRepository>();
         x.For <Logic.Services.IMenuService>().Use <Application.Services.MenuService>();
         x.For <IMenuItemRepository>().Use <MenuItemRepository>();
         x.For <IRestaurantRepository>().Use <RestaurantRepository>();
         x.For <Logic.Services.IRestaurantService>().Use <Application.Services.RestaurantService>();
         x.For <IRestaurantCategoryRepository>().Use <RestaurantCategoryRepository>();
         x.For <Logic.Services.ICustomerService>().Use <Application.Services.CustomerService>();
         x.For <ICustomerRepository>().Use <CustomerRepository>();
         x.For <ICartRepository>().Use <CartRepository>();
         x.For <IOrderRepository>().Use <OrderRepository>();
         x.For <IOrderDetailsRepository>().Use <OrderDetailsRepository>();
         x.For <Logic.Services.ICartService>().Use <Application.Services.CartService>();
         x.For <IOrderStatusRepository>().Use <OrderStatusRepository>();
     });
 }
        public void Setup()
        {
            StructureMapBootStrapper.ConfigureDependencies(StructureMapBootStrapper.DependencyType.TEST);

            ObjectFactory.Configure(cfg => cfg.For <AuthorizationRepTestSupportService>().Use(new AuthorizationRepTestSupportService()).Singleton());
            ObjectFactory.Configure(cfg => cfg.For <IAuthorizationTokenRepository>().Use <AuthorizationRepositorySecurePartTester>());

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                uow.TerminalRepository.Add(new TerminalDO
                {
                    TerminalStatus     = TerminalStatus.Active,
                    Id                 = FixtureData.GetTestGuidById(1),
                    Version            = "v1",
                    Name               = "Test terminal",
                    Label              = "Test",
                    Secret             = Guid.NewGuid().ToString(),
                    Endpoint           = "http://localhost",
                    OperationalState   = OperationalState.Active,
                    ParticipationState = ParticipationState.Approved
                });

                uow.SaveChanges();
            }

            ObjectFactory.GetInstance <AuthorizationRepTestSupportService>().Reset();
        }
        public void Startup(DataStoreType dataStoreType, string connectionString, bool enableCache)
        {
            if (!string.IsNullOrEmpty(connectionString))
            {
                LightSpeedContext context = new LightSpeedContext();
                context.ConnectionString = connectionString;
                context.DataProvider     = dataStoreType.LightSpeedDbType;
                context.IdentityMethod   = IdentityMethod.GuidComb;
                context.CascadeDeletes   = true;

                if (_applicationSettings.IsLoggingEnabled)
                {
                    context.VerboseLogging = true;
                    context.Logger         = new DatabaseLogger();
                }

                if (enableCache)
                {
                    context.Cache = new CacheBroker(new DefaultCache());
                }

                ObjectFactory.Configure(x =>
                {
                    x.For <LightSpeedContext>().Singleton().Use(context);
                    x.For <IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use(ctx => ctx.GetInstance <LightSpeedContext>().CreateUnitOfWork());
                });
            }
            else
            {
                Log.Warn("LightSpeedRepository.Startup skipped as no connection string was provided");
            }
        }
Exemple #18
0
        public static void Configure()
        {
            if (!IsInitialized)
            {
                ObjectFactory.Configure(scanner =>
                {
                    scanner.AddRegistry(new FrameworkRegistry());
                    scanner.AddRegistry(new ServicesRegistry());
                    scanner.AddRegistry(new GeneratorRegistry());
                    scanner.AddRegistry(new Generators.StaticKeyGeneratorLarge.GeneratorRegistry());
                    scanner.AddRegistry(new Providers.AsymmetricEncryptionProvider.ProviderRegistry());
                    scanner.AddRegistry(new Providers.DataGenerationProvider.ProviderRegistry());
                    scanner.AddRegistry(new Providers.HashingProvider.ProviderRegistry());
                    scanner.AddRegistry(new Providers.NetworkTimeProvider.ProviderRegistry());
                    scanner.AddRegistry(new Providers.ObjectSerialization.ProviderRegistry());
                    scanner.AddRegistry(new Providers.SymmetricEncryptionProvider.ProviderRegistry());
                    scanner.AddRegistry(new Providers.WmiDataProvider.ProviderRegistry());
                    scanner.AddRegistry(new ServicesLibraryRegistry());
                    scanner.AddRegistry(new Repositories.ServicesDataRepository.ServicesDataRegistry());
                    scanner.AddRegistry(new Repositories.ClientDataRepository.DataRegistry());
                }
                                        );

                Framework.ObjectLocator.IsInitialized = true;
                IsInitialized = true;
            }
        }
 public static void ConfigurarDependencias()
 {
     ObjectFactory.Configure
         (x =>
         x.AddRegistry(new TestRegistry())
         );
 }
Exemple #20
0
        public void When_resolving_services_from_container_SNAP_should_load_dynamicproxygenassebmly2_in_appdomain_only_once()
        {
            SnapConfiguration.For <StructureMapAspectContainer>(c =>
            {
                c.IncludeNamespaceOf <IBadCode>();
                c.Bind <SecondInterceptor>().To <SecondAttribute>();
                c.Bind <FirstInterceptor>().To <FirstAttribute>();
                c.Bind <HandleErrorInterceptor>().To <HandleErrorAttribute>();
            });

            ObjectFactory.Configure(c => c.For <IOrderedCode>().Use <OrderedCode>());
            ObjectFactory.Configure(c => c.For <IBadCode>().Use <BadCode>());
            var orderedCode = ObjectFactory.GetInstance <IOrderedCode>();
            var badCode     = ObjectFactory.GetInstance <IBadCode>();

            orderedCode.RunInOrder();
            Assert.AreEqual("First", OrderedCode.Actions[1]);
            Assert.AreEqual("Second", OrderedCode.Actions[0]);

            Assert.DoesNotThrow(badCode.GiddyUp);

            var dynamicProxyGenerationAssemblies = AppDomain.CurrentDomain
                                                   .GetAssemblies()
                                                   .Where(assembly => assembly.GetName().Name == "DynamicProxyGenAssembly2")
                                                   .ToList();

            Assert.That(dynamicProxyGenerationAssemblies.Count, Is.EqualTo(2));
            Assert.IsNotNull(dynamicProxyGenerationAssemblies.FirstOrDefault(a => a.GetName().GetPublicKey().Length > 0));
            Assert.IsNotNull(dynamicProxyGenerationAssemblies.FirstOrDefault(a => a.GetName().GetPublicKey().Length == 0));
        }
        private void HandleAdd(IDependencyDefinition dependency)
        {
            var isDuplicate = IsDuplicate(dependency);

            ObjectFactory
            .Configure(x =>
            {
                if (dependency.IsSingleton && !isDuplicate)
                {
                    var singleton = x.For(dependency.PluginType).Singleton();
                    if (dependency.HasSingleton)
                    {
                        singleton.Add(dependency.ConcreteInstance);
                    }
                    else
                    {
                        singleton.Add(dependency.ConcreteType);
                    }
                }
                else if (dependency.IsNamed)
                {
                    x.For(dependency.PluginType).Add(dependency.ConcreteType).Named(
                        dependency.PluginName);
                }
                else if (!isDuplicate)
                {
                    x.For(dependency.PluginType).Add(dependency.ConcreteType);
                }
            });
        }
Exemple #22
0
 public static void Execute()
 {
     ObjectFactory.Configure(i =>
     {
         i.AddRegistry <RegistrationServices>();
     });
 }
Exemple #23
0
        /// <summary>
        /// Instantiates Scheduler, including any configuration.
        /// </summary>
        /// <param name="action">A lambda that configures that sets the Scheduler configuration.</param>
        public static void Initialize(Action <IConfiguration> action = null)
        {
            if (null != _instance)
            {
                throw new Exception("Scheduler cannot be initialized after the Scheduler Instance has been created.");
            }

            var configuration = new Configuration();

            if (null != action)
            {
                action(configuration);
            }

            Configuration = configuration;

            // Ensure container resolves persistance store based on configuration settings
            ObjectFactory.Configure(x => x.RegisterInterceptor(new PersistanceStoreInterceptor(Configuration)));

            // Initialise JobTypes modules
            var jobTypeStartups = ObjectFactory.GetAllInstances <IJobTypeStartup>();

            foreach (var jobTypeStartup in jobTypeStartups)
            {
                jobTypeStartup.Initialise(Configuration);
            }

            if (configuration.AutoStart)
            {
                IScheduler sched = Instance();
                sched.Start();
            }
        }
Exemple #24
0
        public new void Init()
        {
            base.Init();

            ObjectFactory.Configure(x => { x.For <IServiceEndPointFactory>().Use <ServiceEndPointFactory>(); });
            //Ezbob.Backend.Strategies.Library.Initialize(this.m_oEnv, this.m_oDB, this.m_oLog);
        }         // Init
Exemple #25
0
        public void BeforeScenario()
        {
            var transportMock = TransportMock.CreateWithoutStructureMapClear(typeof(SampleProfileSerialized).Assembly,
                                                                             new List <Assembly>
            {
                typeof(ExceptionThrownLocalMessage).Assembly
            },
                                                                             new[] { typeof(WhenAddANewProfileSpecs).Assembly });

            transportMock.AddProfile("Profile_1");

            var mockBufferSize = MockRepository.GenerateStub <IBufferSize>();

            mockBufferSize.Stub(x => x.Value).Return(2);
            ObjectFactory.Configure(x => x.For <IBufferSize>().HybridHttpOrThreadLocalScoped().Use(mockBufferSize));

            ObjectFactory.GetInstance <TransportMock>().On <AddAttachmentPartToMessageCommand>()
            .Reply(x =>
            {
                if (!x.IsLastPart)
                {
                    return(new AttachmentPartAddedMessage {
                        FileName = x.FileName
                    });
                }
                return(new AttachmentCreatedMessage {
                    Dto = new AttachmentDTO {
                        OriginalFileName = x.FileName, OwnerID = x.OwnerId, Description = x.Description
                    }
                });
            });
            Directory.Delete(ObjectFactory.GetInstance <PluginDataFolder>().Path);
        }
Exemple #26
0
        private async static Task Process()
        {
            using (var client = new ChannelTcpClient <object>(
                       new MicroMessageEncoder(new JsonSerializer()),
                       new MicroMessageDecoder(new JsonSerializer())))
            {
                ObjectFactory.Configure(x => x.Scan(z =>
                {
                    z.AssemblyContainingType <IRequestResponseService>();
                    z.With(new ServiceFactoryConvention(new ServiceExecutor(client)));
                    z.AddAllTypesOf <IMicroService>();
                }));


                await client.ConnectAsync(IPAddress.Parse("127.0.0.1"), 1234);

                var srv = ObjectFactory.GetInstance <IRequestResponseService>();

                var result = srv.Call(
                    new TestContract {
                    Text = "Hello text 1"
                },
                    new TestContract {
                    Text = "Hello text 2"
                });

                Console.WriteLine(result);

                await client.CloseAsync();
            }
        }
Exemple #27
0
        public static void Configure()
        {
            ObjectFactory.Configure(c =>
            {
                c.Scan(x =>
                {
                    x.TheCallingAssembly();
                    x.WithDefaultConventions();
                    x.AssemblyContainingType <IFriendsService>(); // Core
                });

                // Configure WebAPI
                c.For <HttpClient>().Singleton().Use(() => ApiConfig.GetClient());

                // Configure Implementations
                //c.For<ISendEmail>().Use<DebugEmailSender>();
                //c.For<IQueryUsersByEmail>().Use<EfQueryUserByEmail>();
                //c.For<IFriendRepository>().Use<EfFriendRepository>();

                // Now we don't need all of the above configure implementations as now we're talking to the api through the below implementations
                // Hence no need to add reference to infrastructure project in this case
                c.For <IUserService>().Use <WebApiUserService>();
                c.For <IFriendsService>().Use <WebApiFriendsService>();
            });
        }
Exemple #28
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => Container ?? ObjectFactory.Container));

            ObjectFactory.Configure(cfg => {
                cfg.AddRegistry(new StandardRegistry());
                cfg.AddRegistry(new ControllerRegistry());
                cfg.AddRegistry(new ActionFilterRegistry(() => Container ?? ObjectFactory.Container));
                cfg.AddRegistry(new MvcRegistry());
                cfg.AddRegistry(new TaskRegistry());
                cfg.AddRegistry(new ModelMetadataRegidrty());
            });

            using (var container = ObjectFactory.Container.GetNestedContainer())
            {
                foreach (var task in container.GetAllInstances <IRunAtInit>())
                {
                    task.Execute();
                }

                foreach (var task in container.GetAllInstances <IRunAtStartup>())
                {
                    task.Execute();
                }
            }
        }
Exemple #29
0
        public override void SetUp()
        {
            base.SetUp();
            var libraryRepositoryFactoryStub = MockRepository.GenerateStub <ILibraryRepositoryFactory>();

            libraryRepositoryFactoryStub
            .Stub(x => x.GetRepository(Arg <LibraryRepositoryConfig> .Is.Anything))
            .WhenCalled(invocation =>
            {
                LibraryRepositoryMock repositoryMock =
                    MockedRepositories.FirstOrDefault(
                        x =>
                        x.Config.Name == ((LibraryRepositoryConfig)invocation.Arguments[0]).Name) ??
                    new LibraryRepositoryMock(
                        (LibraryRepositoryConfig)invocation.Arguments[0]);
                MockedRepositories.Add(repositoryMock);
                invocation.ReturnValue = repositoryMock;
            });
            ObjectFactory.Configure(x =>
            {
                x.For <ILibraryRepositoryFactory>().Use(libraryRepositoryFactoryStub);
                x.For <ILibraryRepositoryConfigStorage>().HybridHttpOrThreadLocalScoped().Use <LibraryRepositoryConfigStorageMock>();
                x.Forward <ILibraryRepositoryConfigStorage, LibraryRepositoryConfigStorageMock>();
            });
        }
Exemple #30
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            ObjectFactory.Configure(c =>
            {
                c.For(typeof(IRepository <>)).Use(typeof(InMemoryCacheRepository <>));
            });

            //We're using Amazon stuff now, no need to configure this.
            //NServiceBus.Configure.WithWeb() //for web apps this should be WithWeb()
            //    .StructureMapBuilder()
            //    .BinarySerializer()
            //    .MsmqTransport()
            //    .MsmqSubscriptionStorage()
            //    .UnicastBus()
            //    .LoadMessageHandlers()
            //    .CreateBus()
            //    .Start();

            Configure.With()
            .StructureMapBuilder(ObjectFactory.Container)
            .CommandExecutorsAreInAssemblyContainingType <CreateMessage>()
            .HandlersAreInAssemblyContainingType <MessageReadModel>()
            .AmazonPublisher()
            .AwsAccessKeyId("AKIAIN2KJH4QJIUV7CGQ")
            .AwsSecretKey("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")
            .TopicArn("arn:aws:sns:us-east-1:451419498740:EventMessage")
            .CreatePublisher();
        }