예제 #1
0
        protected override IContainer InitializeContainer()
        {
            var container = new StructureMap.Container();

            container.Configure(x => x.ForConcreteType <RequestA>().Configure.Named("KeyForRequestA"));
            container.Configure(x => x.ForConcreteType <RequestB>().Configure.Named("KeyForRequestB"));

            return(new Agatha.StructureMap.Container(container));
        }
예제 #2
0
        protected override void PerformSetUp()
        {
            this.UnitOfWork.Session.Save(new Fish
                                     {
                                         Description = "A fish called wanda"
                                     });
            this.UnitOfWork.Session.Save(new Fish
                                     {
                                         Description = "Once up a time in a land called nod."
                                     });
            this.UnitOfWork.Session.Save(new Fish
                                     {
                                         Description = "There was a giant timelord."
                                     });
            this.UnitOfWork.Session.Save(new Fish
                                     {
                                         Description = "There was big and good travel thru time."
                                     });

            this.UnitOfWork.Commit(true);

            var container = new StructureMap.Container();
            container.Configure(x => x.Scan(cfg =>
                                                {
                                                    cfg.TheCallingAssembly();
                                                    cfg.AssemblyContainingType<Fish>();
                                                    cfg.WithDefaultConventions();
                                                }));
            this.fishRepository = new FutureFishNHibernateRepository(this.UnitOfWork);
        }
예제 #3
0
        public void StructureMap()
        {
            var container = new StructureMap.Container();

            foreach (var type in _types)
            {
                container.Configure(c => c.For(type).Use(type));
            }

            int length = 0;

            if (Scenario == ResolveScenario.ResolveOne)
            {
                length = 1;
            }
            else if (Scenario == ResolveScenario.ResolveHalf)
            {
                length = _types.Length / 2;
            }
            else if (Scenario == ResolveScenario.ResolveAll)
            {
                length = _types.Length;
            }

            for (var i = 0; i < length; i++)
            {
                container.GetInstance(_types[i]);
            }

            container.Dispose();
        }
예제 #4
0
        public void Sample()
        {
            var container = new StructureMap.Container();

            container.Configure(c => c.For <ILogger>().Use <ConsoleLogger>());
            ILogger logger = container.GetInstance <ILogger>();
        }
        public static AdaptedContainerBuilderOptions <TTenant> WithStructureMap <TTenant>(
            this ContainerBuilderOptions <TTenant> options,
            Action <TTenant, IServiceCollection> configureTenant)
            where TTenant : class
        {
            var adaptorFactory = new Func <ITenantContainerAdaptor>(() =>
            {
                // host level container.
                var container = new StructureMap.Container();
                container.Populate(options.Builder.Services);
                var adaptedContainer = container.GetInstance <ITenantContainerAdaptor>();

                var containerEventsPublisher = container.TryGetInstance <ITenantContainerEventsPublisher <TTenant> >();
                // add ITenantContainerBuilder<TTenant> service to the host container
                // This service can be used to build a child container (adaptor) for a particular tenant, when required.
                var defaultServices = options.DefaultServices;
                container.Configure(_ =>
                                    _.For <ITenantContainerBuilder <TTenant> >()
                                    .Use(new TenantContainerBuilder <TTenant>(defaultServices, adaptedContainer, configureTenant, containerEventsPublisher))
                                    );

                // NOTE: Im not sure why I was resolving ITenantContainerAdaptor twice, changed to just return previous instance.
                //var adaptor = container.GetInstance<ITenantContainerAdaptor>();
                //return adaptor;
                return(adaptedContainer);
            });

            var adapted = new AdaptedContainerBuilderOptions <TTenant>(options, adaptorFactory);

            return(adapted);
        }
예제 #6
0
        public BusinessTestFixture()
        {
            // Build configuration settings
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            Configuration = builder.Build();
            var appSettings = Configuration.Get<AppSettings>("Application");

            // Start up DI container
            this.container = new StructureMap.Container();
            
            container.Configure(c => c.ForSingletonOf<AppSettings>().Use(appSettings));
            container.Configure(c => c.For<IApplicationContext>().Use<BusinessTestContext>());
            DependencyResolver.RegisterResolver(new StructureMapIOCContainer(container)).RegisterImplmentation();

            // Load mapping            
            LoadAutoMapper();
        }
예제 #7
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var container = new StructureMap.Container(x => {
                x.Scan(y => {
                    y.TheCallingAssembly();
                    y.WithDefaultConventions();
                });
            });

            ServiceLocator.Container = container;

            PageControllerConfiguration.PageDependencyResolver = new StructureMapDependencyResolver(container);

            var eventBus = new UiEventBus();

            container.Configure(x => {
                x.For <LoggingService>().Use <LoggingService>().Singleton();
                x.For <IEventBus>().Use(eventBus);
                x.For <ICrossAppEventBus>().Use(eventBus);
                x.For <IBroadcastService>().Use <BroadcastService>().Singleton();
                x.For <IRequestHandler>().Use <TcpRequestHandler>();
                x.For <AppData>().Use <AppData>().Singleton();
                x.For <Configuration>().Use <Configuration>().Singleton();
                x.For <Game>().Use <Game>().Singleton();
                x.For <IControllerFactory>().Use(new ControllerFactory(container));
            });


            _loggingService = container.GetInstance <LoggingService>();

            var cardLoadService = container.GetInstance <CardLoadService>();

            cardLoadService.RegisterEvents();

            var configurationService = container.GetInstance <ConfigurationService>();

            configurationService.Load();

            var gameFileService = container.GetInstance <GameFileService>();

            gameFileService.Load();

            var receiveSocketService = container.GetInstance <ReceiveSocketService>();

            receiveSocketService.StartListening(TcpInfo.EmoPort);

            var controller = container.GetInstance <MainController>();

            controller.View.Show();
        }
예제 #8
0
        public static void Main(string[] args)
        {
#if DEBUG
            // optional, but recommended
            System.Diagnostics.Debugger.Launch();
#endif
            var container = new StructureMap.Container(x => {
                x.Scan(y => {
                    y.TheCallingAssembly();
                    y.WithDefaultConventions();
                });
            });

            var eventBus = new EventBus();

            container.Configure(x => {
                x.For <IEventBus>().Use(eventBus);
                x.For <ICrossAppEventBus>().Use(eventBus);
                x.For <ICardGroupStore>().Use <CardGroupStore>().Singleton();
                x.For <IDynamicActionManager>().Use <DynamicActionManager>().Singleton();
                x.For <IDynamicActionInfoStore>().Use <DynamicActionInfoStore>().Singleton();
                x.For <ISendEventHandler>().Use <SendEventHandler>().Singleton();
                x.For <IImageService>().Use <ImageService>().Singleton();
                x.For <ITcpRequestHandler>().Use <TcpRequestHandler>().Singleton();
                x.For <IRequestHandler>().Use(c => c.GetInstance <ITcpRequestHandler>());
                x.For <IReceiveSocketService>().Use <ReceiveSocketService>();
                x.For <IEstablishConnectionToUiService>().Use <EstablishConnectionToUiService>();
            });

            ServiceLocator.Container = container;

            //keep references or garbage collection will clean this up and we'll stop receiving events
            var sendEventHandler     = container.GetInstance <ISendEventHandler>();
            var receiveSocketService = container.GetInstance <IReceiveSocketService>();
            receiveSocketService.StartListening(StreamDeckTcpInfo.Port);

            var establishConnectionToUiService = container.GetInstance <IEstablishConnectionToUiService>();
            establishConnectionToUiService.AttemptToEstablishConnection();

            // register actions and connect to the Stream Deck
            SharpDeck.StreamDeckPlugin.Run();
        }
예제 #9
0
        public static void Execute()
        {
            var container = new StructureMap.Container();

            container.Configure(c =>
            {
                c.Scan(x =>
                {
                    x.AssembliesFromApplicationBaseDirectory();
                    x.WithDefaultConventions();
                    x.LookForRegistries();
                });
                c.SetAllProperties(x =>
                                   x.TypeMatches(
                                       type => container.Model.HasImplementationsFor(type)));
            });

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
            FilterProviders.Providers.Add(new StructureMapFilterAttributeFilterProvider(container));
        }
        static IContainer BootstrapContainer()
        {
            var container = new Container(x => { x.AddType(typeof(OrderForm)); });

            container.Configure(cfg =>
            {
                cfg.For<IServiceBus>().Use(context => ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom("msmq://localhost/starbucks_customer");
                    sbc.UseMsmq();
                    sbc.UseMulticastSubscriptionClient();

                    sbc.UseControlBus();

                    sbc.Subscribe(subs => { subs.LoadFrom(container); });
                }));
            });

            return container;
        }
예제 #11
0
        /// <summary>
        /// Custom initialization logic where you would tell StructureMap which
        /// implementations to use for each interface class.
        /// </summary>
        /// <param name="container"></param>
        protected override void ClientInit(StructureMap.Container container)
        {
            container.Configure(x =>
            {
                x.For <ISecurityProvider>().Use <SecurityProvider>();
                x.For <IUserProvider>().Use <SessionUserProvider>();
                x.For <ISendMailProvider>().Use(() => new SendMailProvider());
                x.For <IApplicationMembershipProvider>().Use <FormsApplicationMembershipProvider>();
                x.For <ITokenResolver>().Use <TokenResolver>();
                x.For <ITokenResolutionProvider>().Use <TokenResolutionProvider>();
                x.For <IDomainLoginService>().Use <DomainLoginService>();
                x.For <IDomainLogoutService>().Use <DomainLogoutService>();

                /*
                 * TODO:  Choose the appropriate membership provider if you need a custom one, and then remove the Forms
                 * membership provider above.
                 * x.For<IApplicationMembershipProvider>().Use<ApplicationMembershipProvider>();
                 */
            });
        }
예제 #12
0
        static IContainer BootstrapContainer()
        {
            var container = new Container(x => { x.AddType(typeof(OrderForm)); });

            container.Configure(cfg =>
            {
                cfg.For <IServiceBus>().Use(context => ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom("msmq://localhost/starbucks_customer");
                    sbc.UseMsmq();
                    sbc.UseMulticastSubscriptionClient();

                    sbc.UseControlBus();

                    sbc.Subscribe(subs => { subs.LoadFrom(container); });
                }));
            });

            return(container);
        }
예제 #13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var container = new StructureMap.Container(x => {
                x.Scan(y => {
                    y.TheCallingAssembly();
                    y.WithDefaultConventions();
                });
            });

            PageControllerConfiguration.PageDependencyResolver = new StructureMapDependencyResolver(container);

            _loggingService = new LoggingService();

            container.Configure(x => {
                x.For <IRequestHandler>().Use <TcpRequestHandler>();
                x.For <AppData>().Use(new AppData());
                x.For <IControllerFactory>().Use(new ControllerFactory(container));
                x.For <LoggingService>().Use(_loggingService);
            });

            var cardLoadService = container.GetInstance <CardLoadService>();

            cardLoadService.RegisterEvents();

            var configurationService = container.GetInstance <ConfigurationService>();

            configurationService.Load();

            var gameFileService = container.GetInstance <GameFileService>();

            gameFileService.Load("LastSaved.json");

            var receiveSocketService = container.GetInstance <ReceiveSocketService>();

            receiveSocketService.StartListening(TcpInfo.ArkhamOverlayPort);

            var controller = container.GetInstance <MainController>();

            controller.View.Show();
        }
예제 #14
0
        //TODO: consolidate DI
        public NsqInboundMessageQueue(IMessageDispatcher dispatcher, ILogger logger,
                                      NsqConfiguration configuration)
        {
            foreach (var item in configuration.MessageTypeTopics.Keys)
            {
                MessageTypes.Add(item);
            }

            var structureMapContainer = new StructureMap.Container();

            structureMapContainer.Configure(p =>
            {
                p.Scan(x =>
                {
                    x.TheCallingAssembly();
                    x.WithDefaultConventions();
                });

                p.For <IMessageDispatcher>().Use(dispatcher);
                p.For <ILogger>().Use(logger);
            });

            var messageTopics   = new Dictionary <Type, string>(configuration.MessageTypeTopics);
            var handlerChannels = new Dictionary <Type, string>(configuration.MessageHandlerTypeChannels);

            _busConfiguration = new BusConfiguration(
                new StructureMapObjectBuilder(structureMapContainer),       // dependency injection container
                new NewtonsoftJsonSerializer(typeof(JsonConvert).Assembly), // message serializer
                new MessageAuditor(),                                       // receives received, started, and failed notifications
                new MessageTypeToTopicProvider(                             // mapping between .NET message types and topics
                    messageTopics
                    ),
                new HandlerTypeToChannelDictionary( // mapping between IHandleMessages<T> implementations and channels
                    handlerChannels
                    ),
                preCreateTopicsAndChannels: true,                                   // pre-create topics so we dont have to wait for an nsqlookupd cycle
                defaultNsqLookupdHttpEndpoints: configuration.LookupdHttpEndpoints, // nsqlookupd address
                defaultThreadsPerHandler: 1,                                        // threads per handler. tweak based on use case, see handlers in this project.
                logOnProcessCrash: true
                );
        }
예제 #15
0
        public void RegisterImplmentation()
        {
            // Auto register
            var odtLibraries = GetReferencingAssemblies("OnDemandTools")
                               .SelectMany(assembly => assembly.ExportedTypes)
                               .ToList();


            var profiles = odtLibraries.Where(t => t.GetTypeInfo().IsClass &&
                                              !t.GetTypeInfo().IsAbstract &&
                                              !t.GetTypeInfo().IsInterface).ToList();


            cntr.Configure(c =>
            {
                foreach (var item in profiles)
                {
                    var ints = item.GetInterfaces();
                    foreach (var it in ints)
                    {
                        if (it.ToString().StartsWith("OnDemandTools", StringComparison.OrdinalIgnoreCase))
                        {
                            c.AddType(it, item);
                        }
                    }
                }



                // Add those that cannot be auto registered. Basically the ones outside 'OnDemandTools' namespace or
                // someother special case
                c.For <IODTDatastore>().Use <ODTPrimaryDatastore>();

                // Special initialization for StatusLibrary class
                OnDemandTools.DAL.Modules.Reporting.Library.StatusLibrary.Init((AppSettings)cntr.GetInstance(typeof(AppSettings)));
            });
        }
        public static void Register()
        {
            s_container.Configure(
                x => x.For <IWebService>()
                .Use(c => new WebService(
                         c.GetInstance <IAuthenticator>(),
                         c.GetInstance <IStockQuote>())));

            s_container.Configure(
                x => x.For <IAuthenticator>()
                .Use(c => new Authenticator(
                         c.GetInstance <ILogger>(),
                         c.GetInstance <IErrorHandler>(),
                         c.GetInstance <IDatabase>())));

            s_container.Configure(
                x => x.For <IStockQuote>()
                .Use(c => new StockQuote(
                         c.GetInstance <ILogger>(),
                         c.GetInstance <IErrorHandler>(),
                         c.GetInstance <IDatabase>())));

            s_container.Configure(
                x => x.For <IDatabase>()
                .Use(c => new Database(
                         c.GetInstance <ILogger>(),
                         c.GetInstance <IErrorHandler>())));

            s_container.Configure(
                x => x.For <IErrorHandler>()
                .Use(c => new ErrorHandler(c.GetInstance <ILogger>())));

            s_container.Configure(
                x => x.For <ILogger>()
                .Use(new Logger()));

            Assembly messages = Assembly.Load("BonusBits.CodeSamples.Agatha.Messages");

            new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(),
                                          messages, new global::Agatha.StructureMap.Container(s_container)).Initialize();
        }
예제 #17
0
        public override bool Execute()
        {
            if (TargetSitemapsFiles == null && TargetProjectFiles == null && TargetUrls == null)
            {
                Log.LogError("You must specify at least 1 url in order to run the task. " +
                    "The urls can be provided through TargetUrls, TargetProjectFiles, or TargetSitemapFiles.");
                return false;
            }

            // Setup configuration of DI container
            Log.LogMessage(MessageImportance.Low, "Composing Application");
            var container = new StructureMap.Container();
            container.Configure(r => r.AddRegistry<HtmlValidatorRegistry>());

            // Add the current parameters to context
            Log.LogMessage(MessageImportance.Low, "Creating Context");

            var context = new HtmlValidatorRunnerContext(new ConsoleAnnouncer())
            {
                TargetSitemapsFiles = this.TargetSitemapsFiles.ToStringArray(),
                TargetUrls = this.TargetUrls.ToStringArray(),
                TargetProjectFiles = this.TargetProjectFiles.ToStringArray(),
                UrlReplacementArgs = this.UrlReplacementArgs.ToStringArray(),
                OutputPath = this.OutputPath,
                OutputFormat = this.OutputFormat,
                ValidatorUrl = this.ValidatorUrl,
                DirectInputMode = this.DirectInputMode,
                CharSet = this.CharSet,
                DocType = this.DocType,
                Verbose = this.Verbose,
                Debug = this.Debug,
                ShowSource = this.ShowSource,
                Outline = this.Outline,
                GroupErrors = this.GroupErrors,
                UseHtmlTidy = this.UseHtmlTidy
            };

            // Setup the container to use the context as a singleton so it is available everywhere.
            container.Configure(r => r.For<IHtmlValidatorRunnerContext>().Singleton().Use(x => context));
            container.Configure(r => r.For<IValidatorRunnerContext>().Singleton().Use(x => context));
            container.Configure(r => r.For<IRunnerContext>().Singleton().Use(x => context));

            var runner = container.GetInstance<IValidatorRunner>();

            Log.LogMessage(MessageImportance.Low, "Starting Runner");

            try
            {
                // get output information (errors, warnings)
                var report = runner.Execute();

                this.TotalErrors = report.TotalErrors;
                this.TotalWarnings = report.TotalWarnings;
            }
            catch (Exception ex)
            {
                Log.LogError("While executing validation the following error was encountered: {0}, {1}", ex.Message, ex.StackTrace);
                return false;
            }

            return true;
        }