// This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });
            services.AddTransient <IMessageBuilder <VirtualCloset, VirtualClosetResponse>, VirtualClosetResponseBuilder>();
            services.AddTransient <IVirtualClosetDao, VirtualClosetDao>();
            services.AddTransient <ICategoryManager, CategoryManager>();
            services.AddTransient <IVirtualClosetManager, VirtualClosetManager>();
            services.AddDbContext <VirtualClosetContext>(opt =>
            {
                opt.UseSqlServer(Configuration.GetConnectionString("VirtualClosetDb"));
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var container = new Container();

            container.Configure(config =>
            {
                config.Populate(services);
                config.For <IServiceLocator>().Singleton().Use(new StructureMapServiceLocator(container));
            });

            var registrar = new StructureMapRegistrar(container);

            registrar.Register <BaseRegistry>();

            return(new StructureMapServiceProvider(container));
        }
示例#2
0
        private IMediator FromStructureMap(StringWriter writer)
        {
            var container = new StructureMap.Container(cfg =>
            {
                cfg.Scan(scanner =>
                {
                    scanner.AssemblyContainingType <CustomNotification>();
                    scanner.AssemblyContainingType <IMediator>();
                    scanner.WithDefaultConventions();
                    scanner.AddAllTypesOf(typeof(IRequestHandler <,>));
                    scanner.AddAllTypesOf(typeof(INotificationHandler <>));
                });
                //cfg.Scan(scanner =>
                //{
                //    scanner.AssemblyContainingType<CustomNotification>();
                //    scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                //    scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                //    scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                //});

                //Constrained notification handlers
                cfg.For(typeof(INotificationHandler <>)).Add(typeof(CustomNotificationHandler <>));

                // This is the default but let's be explicit. At most we should be container scoped.
                cfg.For <IMediator>().LifecycleIs <TransientLifecycle>().Use <Mediator>();

                cfg.For <SingleInstanceFactory>().Use <SingleInstanceFactory>(ctx => ctx.GetInstance);
                cfg.For <MultiInstanceFactory>().Use <MultiInstanceFactory>(ctx => ctx.GetAllInstances);
                cfg.For <TextWriter>().Use(writer);
            });

            var mediator = container.GetInstance <IMediator>();

            return(mediator);
        }
        static StructureMapSingletonUseCase()
        {
            container = new StructureMap.Container();
            container.Configure(
                x => x.For <IWebService>()
                .Use <WebService>());

            container.Configure(
                x => x.For <IAuthenticator>().Singleton()
                .Use <Authenticator>());

            container.Configure(
                x => x.For <IStockQuote>().Singleton()
                .Use <StockQuote>());

            container.Configure(
                x => x.For <IDatabase>().Singleton()
                .Use <Database>());

            container.Configure(
                x => x.For <IErrorHandler>().Singleton()
                .Use <ErrorHandler>());

            container.Configure(
                x => x.For <ILogger>().Singleton()
                .Use(c => new Logger()));
        }
        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>();
                // 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.
                container.Configure(_ =>
                                    _.For <ITenantContainerBuilder <TTenant> >()
                                    .Use(new TenantContainerBuilder <TTenant>(adaptedContainer, configureTenant))
                                    );

                var adaptor = container.GetInstance <ITenantContainerAdaptor>();
                return(adaptor);
            });

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

            options.Builder.Services.TryAddScoped((_) => adapted);

            return(adapted);
        }
        public async Task Options_Configure_Child_Resolve_Child_Using_TenantContainerAdaptor()
        {
            ServiceCollection services = new ServiceCollection();

            services.AddLogging();

            //  ServiceProvider serviceProvider = services.BuildServiceProvider();


            StructureMap.Container container = new StructureMap.Container();
            Dotnettency.Container.StructureMap.ContainerExtensions.Populate(container, services);

            var adaptedContainer         = container.GetInstance <ITenantContainerAdaptor>();
            var containerEventsPublisher = container.TryGetInstance <ITenantContainerEventsPublisher <MyTenant> >();

            container.Configure(_ =>
                                _.For <ITenantContainerBuilder <MyTenant> >()
                                .Use(new TenantContainerBuilder <MyTenant>(services, adaptedContainer, (s, t) => {
                t.AddOptions();
                t.Configure <MyOptions>((a) =>
                {
                    a.Prop = true;
                });
            }, containerEventsPublisher))
                                );

            // container.Populate(services);

            var tenantContainerBuilder = adaptedContainer.GetRequiredService <ITenantContainerBuilder <MyTenant> >();
            var tenantContainer        = await tenantContainerBuilder.BuildAsync(new MyTenant());

            IOptions <MyOptions> options = tenantContainer.GetRequiredService <IOptions <MyOptions> >();

            Assert.True(options.Value?.Prop);
        }
        public void Options_Populate_Root_Resolve_Nested_Using_TenantContainerAdaptor()
        {
            ServiceCollection services = new ServiceCollection();

            services.AddOptions();
            services.AddLogging();
            services.Configure <MyOptions>((a) =>
            {
                a.Prop = true;
            });
            ServiceProvider serviceProvider = services.BuildServiceProvider();


            StructureMap.Container container = new StructureMap.Container();
            Dotnettency.Container.StructureMap.ContainerExtensions.Populate(container, services);

            // container.Populate(services);

            ITenantContainerAdaptor sp = container.GetInstance <ITenantContainerAdaptor>();

            ITenantContainerAdaptor childSp = sp.CreateChildContainer("Child");
            var nestedSp = childSp.CreateChildContainer("Nested");


            IOptions <MyOptions> options = nestedSp.GetRequiredService <IOptions <MyOptions> >();

            Assert.True(options.Value?.Prop);
        }
示例#7
0
        static void Main(string[] args)
        {
            var container = new StructureMap.Container(new MultithreadRegistry());
            var startApp  = container.GetInstance <StartApp>();

            startApp.Run();
        }
        public void HttpClient()
        {
            var services = new ServiceCollection();

            services.AddHttpClient("client")
            .AddHttpMessageHandler <RequestContentMd5Handler>()
            .AddHttpMessageHandler <HmacSigningHandler>();

            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                config.For <ISecretRepository>().Singleton().Use(new SecretStore());

                config.For <ISignatureCalculator>().Use <HmacSignatureCalculator>();
                config.For <IMessageRepresentationBuilder>().Use <HmacMessageRepresentationBuilder>();

                config.For <RequestContentMd5Handler>().Use <RequestContentMd5Handler>();
                config.For <HmacSigningHandler>().Use <HmacSigningHandler>();

                config.Populate(services);
            });

            var serviceProvider = container.GetInstance <IServiceProvider>();

            var factory = serviceProvider.GetService <IHttpClientFactory>();

            factory.CreateClient("client");
        }
示例#9
0
        public static ContainerBuilderOptions <TTenant> WithStructureMapServiceCollection <TTenant>(this ContainerBuilderOptions <TTenant> options,
                                                                                                    Action <TTenant, IServiceCollection> configureTenant)
            where TTenant : class
        {
            // Set a func, that is only invoked when the ServiceProvider is required. This ensures it runs after all other configuration methods
            // which is important as other methods can still add new services to the servicecollection after this one is invoked and we
            // dont want them to be missed when populating the container.
            options.Builder.BuildServiceProvider = new Func <IServiceProvider>(() =>
            {
                var container = new StructureMap.Container();
                container.Populate(options.Builder.Services);

                container.Configure(_ =>
                                    _.For <ITenantContainerBuilder <TTenant> >()
                                    .Use(new StructureMapTenantContainerBuilder <TTenant>(container, (tenant, configurationExpression) =>
                {
                    var tenantServices = new ServiceCollection();
                    configureTenant(tenant, tenantServices);
                    configurationExpression.Populate(tenantServices);
                }))
                                    );

                // now configure nested container per tenant.
                return(container.GetInstance <IServiceProvider>());
            });

            return(options);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });
            services.AddTransient <IMessageBuilder <TodoItem, TodoItemResponse>, TodoItemResponseBuilder>();
            services.AddTransient <ITodoItemsManager, TodoItemsManager>();
            services.AddTransient <ITodoItemsDao, TodoItemsDao>();
            services.AddDbContext <TodoContext>(opt =>
                                                { opt.UseSqlServer(Configuration.GetConnectionString("TodoDb")); });

            services.AddMvc();

            // Wire up StructureMap
            var container = new Container();

            container.Configure(config =>
            {
                config.Populate(services);
                config.For <IServiceLocator>().Singleton().Use(new StructureMapServiceLocator(container));
            });

            var registrar = new StructureMapRegistrar(container);

            registrar.Register <BaseRegistry>();

            return(new StructureMapServiceProvider(container));
        }
        private static void BenchStructureMap()
        {
            var services = new ServiceCollection();

            services.AddScoped <IValueProvider, ValueProvider>();
            services.AddLogging();

            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Program));
                    _.WithDefaultConventions();
                });
                config.Populate(services);
            });

            Launch("StructureMap", (i) =>
            {
                var valueProvider = container.GetInstance <IValueProvider>();
                valueProvider.GetValue(i);
            });
        }
        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);

            var container = new StructureMap.Container(cfg =>
            {
                cfg.For <ConfigurationPropertyHolder>().Singleton().Use(configuration_property_holder);
                cfg.For <FileSystemAccess>().Singleton().Use(context => new DotNetFileSystemAccess(configuration_property_holder));
                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 <EnvironmentSet>().Singleton().Use(new DefaultEnvironmentSet(configuration_property_holder));
                cfg.For <Initializer>().Singleton().Use <FileSystemInitializer>();
            });

            // forcing a build of database to initialize connections so we can be sure server/database have values
            Database database = container.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(container));
        }
示例#13
0
        public IContainer Bootstrap()
        {
            _log.Debug("Bootstrapping container");

            IContainer container = new StructureMap.Container(x =>
                {
                    x.For<NuConventions>().Singleton().Use<DefaultNuConventions>();

                    x.For<NugsDirectory>().Singleton().Use<DotNetNugsDirectory>();
                    x.For<InstallationDirectory>().Singleton().Use<DotNetInstallationDirectory>();
                    x.For<CurrentWorkingDirectory>().Singleton().Use<DotNetCurrentWorkingDirectory>();

                    x.For<DefaultsConfiguration>().Singleton().Use<FileBasedDefaultsConfiguration>();
                    x.For<GlobalConfiguration>().Singleton().Use<FileBasedGlobalConfiguration>();
                    x.For<ProjectConfiguration>().Singleton().Use<FileBasedProjectConfiguration>();

                    x.For<FileSystem>().Singleton().Use<DotNetFileSystem>();
                });

            ScanForExtensions(container);

            ScanForImplementations(container);

            return container;
        }
        public void BootstrapStructureMap()
        {
            var registry = new Registry();

            registry.Scan(scan =>
            {
                scan.TheCallingAssembly();

                if (_namespacesToScan != null)
                {
                    foreach (var name in _namespacesToScan)
                    {
                        scan.AssembliesFromApplicationBaseDirectory(assembly => assembly.GetName().Name.StartsWith(name));
                    }
                }

                scan.LookForRegistries();

                scan.RegisterConcreteTypesAgainstTheFirstInterface();
                scan.WithDefaultConventions();
            });

            var container = new StructureMap.Container(registry);

            //var whatIHave = container.WhatDoIHave();
            //container.AssertConfigurationIsValid();

            Container.TheContainer = container;
        }
示例#15
0
 public void ServiceLocatorProviderInstanceShouldBeCreatedWithEmptyCompositionRoot()
 {
     using (var container = new StructureMap.Container())
     {
         ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(container));
         Assert.That(ServiceLocator.Current, Is.Not.Null);
     }
 }
示例#16
0
文件: Startup.cs 项目: KhaledSMQ/aml
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection_" + Helper.GetPlatform().ToString())));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc();

            services.AddMvc().AddControllersAsServices();

            services.AddMvc()
            .AddSessionStateTempDataProvider()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            });

            services.AddSession();

            var z = new Registry();

            z.Scan(x =>
            {
                x.TheCallingAssembly();
                x.Assembly("As.A4ACore");
                x.Assembly("As.Email");
                x.SingleImplementationsOfInterface();
                x.WithDefaultConventions();
            });

            var container = new StructureMap.Container();

            services.AddSingleton <Container>(container);

            container.Configure(config =>
            {
                config.Populate(services);
                config.AddRegistry(z);
                config.ForConcreteType <A4ARepository>().Configure.Ctor <string>("connectionString").Is(Configuration.GetConnectionString("MainLogic_" + Helper.GetPlatform().ToString()));
            });

            var loggerAdapter = container.GetInstance <A4ALogger>();

            L.SetExternalLogger(loggerAdapter, AsLogInfo.Info);



            return(container.GetInstance <IServiceProvider>());
        }
 public void Should_Remember_How_To_Work_With_SM()
 {
     using (StructureMap.Container container = new StructureMap.Container())
     {
         container.Configure(c =>
         {
             c.For<ILatLong>().Add<LatLong>();
         });
         Console.WriteLine(container.GetInstance<ILatLong>().GetType().Name);
     }
 }
示例#18
0
文件: Startup.cs 项目: KhaledSMQ/aml
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddControllersAsServices();

            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                config.Populate(services);
            });

            As.Client.InitializeClient.StartupAndRegisterClientServices(Configuration, container);
            return(container.GetInstance <IServiceProvider>());
        }
示例#19
0
        private IServiceProvider ConfigStructureMapDI(IServiceCollection services)
        {
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                config.For <IRequestIdFactory>().Use <RequestIdFactory>().Singleton();
                config.For <IRequestId>().Use <RequestId>().ContainerScoped();

                config.Populate(services);
            });

            return(container.GetInstance <IServiceProvider>());
        }
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public static IContainer Initialize()
 {
     var container = new StructureMap.Container();
     container.Configure(cfg =>
     {
         cfg.Scan(s =>
         {
             s.WithDefaultConventions();
             s.Assembly(Assembly.GetAssembly(typeof(BaseOperation<,>)));
             s.Assembly(Assembly.GetAssembly(typeof(BaseService<>)));
         });
         cfg.For<IKarinUnitOfWork>().Use<KarinContext>();
     });
     return container;
     //new Container(c => c.AddRegistry<DefaultRegistry>());
 }
示例#21
0
        private static StructureMap.Container ContainerDefault()
        {
            var container = new StructureMap.Container(x =>
            {
                x.Scan(scanner =>
                {
                    scanner.Assembly(typeof(CategoryService).Assembly);
                    scanner.WithDefaultConventions();
                });

                x.AddRegistry <DbContextRegistery>();
                x.AddRegistry <IdentityRegistery>();
            });

            return(container);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IContainer myContainer = new StructureMap.Container();

            var bus = Bus.Initialize(config =>
            {
                config.SetContainer(myContainer);
                config.ScanForMesssageHandlers = true;
                config.SetHost("localhost");
            });

            //bus.RunWebApiHost(new[] { "http://localhost:5050", "http://localhost:5051" });
            //bus.RunWebApiHost("http://localhost:5050");
            bus.RunWebApiHost();
        }
        private IServiceProvider ConfigureIoc(IServiceCollection services)
        {
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                config.Scan(scanner =>
                {
                    scanner.AssemblyContainingType(typeof(Startup));
                    scanner.WithDefaultConventions();
                });

                config.Populate(services);
            });

            return(container.GetInstance <IServiceProvider>());
        }
示例#24
0
        public static void Start()
        {
			// TODO - move declarations into a registry
			var container = new Container(x =>
			{

				x.For<IDocumentSession>()
					.HttpContextScoped()
					.Use(c => DocumentStoreHolder.DocumentStore.OpenSession());

				x.For<IHomepageContentProvider>().Use<HomepageContentProvider>();

				x.For<IBookCreater>().Use<BookCreater>();

				x.For<ImagePreparer>().Use<SimpleImagePreparer>();

				x.For<IBookUpdater>().Use<RavenDbBookUpdater>();

				x.For<IGenreRetriever>().Use<RavenDbGenreRetriever>();

				x.For<IGenreCreater>().Use<RavenDbGenreCreater>();

				x.For<IBookRetriever>().Use<RavenDbBookRetriever>();

				x.For<IBlogPostsRetriever>().Use<BlogPostsRetriever>();

				x.For<ITweetRetriever>().Use<AsyncTimeoutTweetRetriever>();

				x.For<IAboutInfoRetriever>().Use<RavenAboutInfoRetriever>();

				x.For<IAboutInfoUpdater>().Use<RavenAboutInfoUpdater>();

				x.For<IDoorStaff>().Use<HardBastardsDoorStaff>();

				x.For<IValidator>().Use(Validator.BasicValidator);

				x.For<IValidationContinuationHandler>().Use<ValidationContinuationHandler>();

				x.For<IContinuationDirector>().Use<ContinuationHandler>();

				x.For<IActionFinder>().Use<BehaviourGraphActionFinder>();
			});

        	BootstrappingExtensions.StructureMap(FubuApplication.For<NTCodingFubuRegistry>(), container)
                .Bootstrap();
        }
示例#25
0
        static void Main(string[] args)
        {
            Console.WriteLine("*********** Consumer ***********");

            IContainer myContainer = new StructureMap.Container();

            var depdulicationSettings = DeduplicationFilterSettings.Instance;

            depdulicationSettings.ConnectionStringMongoDb   = ConfigurationManager.AppSettings["ServiceConnectPersistorConnectionString"];
            depdulicationSettings.DatabaseNameMongoDb       = "MessageDeduplication";
            depdulicationSettings.CollectionNameMongoDb     = ConfigurationManager.AppSettings["EndPoint"];
            depdulicationSettings.MsgCleanupIntervalMinutes = 6 * 60; // Every 6 hours
            depdulicationSettings.MsgExpiryHours            = 7 * 24; // 1 week

            var bus = Bus.Initialize(config =>
            {
                config.TransportSettings.SslEnabled = true;
                config.TransportSettings.Certs      = new X509Certificate2Collection
                {
                    new X509Certificate2(Convert.FromBase64String(ConfigurationManager.AppSettings["RabbitMqCertBase64"]),
                                         ConfigurationManager.AppSettings["RabbitMqCertPassword"])
                };
                config.TransportSettings.Username   = ConfigurationManager.AppSettings["RabbitMQUsername"];
                config.TransportSettings.Password   = ConfigurationManager.AppSettings["RabbitMqPassword"];
                config.TransportSettings.ServerName = ConfigurationManager.AppSettings["RabbitMqHostname"];
                config.TransportSettings.Version    = SslProtocols.Default;
                config.ScanForMesssageHandlers      = true;
                config.SetThreads(20);
                config.SetContainer(myContainer);
                config.SetAuditingEnabled(true);

                config.BeforeConsumingFilters.Add(typeof(IncomingDeduplicationFilterMongoDbSsl));
                config.BeforeConsumingFilters.Add(typeof(TokenDecryptFilter));
                config.AfterConsumingFilters.Add(typeof(OutgoingDeduplicationFilterMongoDbSsl));
                config.OutgoingFilters.Add(typeof(TokenInjectTokenFilter));

                config.TransportSettings.MaxRetries = 0;
            });

            bus.StartConsuming();

            Console.ReadLine();

            bus.Dispose();
        }
示例#26
0
        public static IContainer Initialize()
        {
            var container = new StructureMap.Container();

            container.Configure(cfg =>
            {
                cfg.Scan(s =>
                {
                    s.WithDefaultConventions();
                    s.Assembly(Assembly.GetAssembly(typeof(BaseOperation <,>)));
                    s.Assembly(Assembly.GetAssembly(typeof(BaseService <>)));
                });
                cfg.For <IFiberUnitOfWork>().Use <FiberContext>();
            });

            return(container);
            //new Container(c => c.AddRegistry<DefaultRegistry>());
        }
示例#27
0
        static void Main(string[] args)
        {
            Console.WriteLine("*********** Consumer ***********");

            IContainer myContainer = new StructureMap.Container();

            var bus = Bus.Initialize(config =>
            {
                config.SetContainer(myContainer);
                config.SetQueueName("PointToPoint.Consumer");
            });

            bus.StartConsuming();

            Console.WriteLine("Connected");

            Console.ReadLine();

            bus.Dispose();
        }
        public void Options_Configure_Root_Resolve_Root()
        {
            // ServiceProvider serviceProvider = services.BuildServiceProvider();
            StructureMap.Container container = new StructureMap.Container();
            container.Configure((a) => {
                ServiceCollection services = new ServiceCollection();
                services.AddOptions();
                services.Configure <MyOptions>((b) =>
                {
                    b.Prop = true;
                });
                a.Populate(services);
            });

            // container.Populate(services);

            IServiceProvider     sp      = container.GetInstance <IServiceProvider>();
            IOptions <MyOptions> options = sp.GetRequiredService <IOptions <MyOptions> >();

            Assert.True(options.Value?.Prop);
        }
        private IServiceProvider ConfigureStructureMap(IServiceCollection services)
        {
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    // Automatically register services that follow default conventions, e.g.
                    // PurchasingService/IPurchasingService
                    // ConcreteService (concrete types can always be resolved)
                    // Typically, you will have a lot of Service/IService pairs in your app
                    _.AssemblyContainingType(typeof(Startup));
                    _.WithDefaultConventions();
                    // Register all of the implementations of IGamingService
                    // CrosswordService
                    // SudokuService
                    _.AddAllTypesOf <IGamingService>();
                    // Register all non-generic implementations of IValidatior<T> (UserModelValidator)
                    _.ConnectImplementationsToTypesClosing(typeof(IValidator <>));
                });

                // When a ILeaderboard<T> is requested, use Leaderboard<T>
                config.For(typeof(ILeaderboard <>)).Use(typeof(Leaderboard <>));
                // When an IUnitOfWork<T> is requested, run the lambda
                // Also, has a "scoped" lifetime, instead of the default "transient" lifetime
                config.For <IUnitOfWork>().Use(_ => new UnitOfWork(3)).ContainerScoped();
                // For a given T, when an IValidator<T> is requested,
                // but there are no non-generic implementations of IValidator<T>
                // Use DefaultValidator<T> instead
                config.For(typeof(IValidator <>)).Add(typeof(DefaultValidator <>));

                //Populate the container using the service collection
                config.Populate(services);
            });

            //Return the IServiceProvider. This tells ASP.NET Core to use StructureMap to resolve dependencies
            return(container.GetInstance <IServiceProvider>());
        }
示例#30
0
        public static void Main(string[] args)
        {
            Console.WriteLine("*********** Consumer ***********");

            IContainer myContainer = new StructureMap.Container();

            var bus = Bus.Initialize(config =>
            {
                config.SetContainer(myContainer);
                config.SetThreads(1);
                //config.SetContainerType<DefaultBusContainer>();
                config.SetHost("localhost");
                config.TransportSettings.ClientSettings.Add("PrefetchCount", 7);
                config.TransportSettings.ClientSettings.Add("HeartbeatEnabled", true);
                //config.TransportSettings.ClientSettings.Add("DisablePrefetch", true);
            });

            bus.StartConsuming();

            Console.ReadLine();

            bus.Dispose();
        }
示例#31
0
        private static void ConfigureServices(IServiceCollection services)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            services
            .AddLogging(configure => configure.AddSerilog());

            // add StructureMap
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Program));
                    _.WithDefaultConventions();
                });
                // Populate the container using the service collection
                config.Populate(services);
            });
        }
示例#32
0
        public IServiceProvider ConfigureIoC(IServiceCollection services)
        {
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.WithDefaultConventions();
                    _.AddAllTypesOf <IPhotoService>();
                    _.AddAllTypesOf <IAlbumService>();
                });
                services.AddScoped <IPhotoService, PhotoService>();
                services.AddScoped <IAlbumService, AlbumService>();
                services.Add(ServiceDescriptor.Transient(typeof(IRepository <>), typeof(Repository <>)));

                //Populate the container using the service collection
                config.Populate(services);
            });

            return(container.GetInstance <IServiceProvider>());
        }
        public PlateletActiveService()
        {
            InitializeComponent();

            // Initialize the log.
            if (!System.Diagnostics.EventLog.SourceExists("PlateletActiveService"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "PlateletActiveService", "");
            }
            eventLog1.Source = "PlateletActiveService";

            eventLog1.Log = "";

            eventLog1.WriteEntry("PlateletActive Service initiating...");

            var container = new StructureMap.Container(c => c.AddRegistry<PlateletActive.CompositionRoot.DefaultRegistry>());

            _hplcDataService = container.GetInstance<IHplcDataService>();

            // Initialize the maintenance timer.
            int minutesTemp = 10;

            var minutes = Int32.TryParse(ConfigurationManager.AppSettings["minutes"], out minutesTemp) ? minutesTemp : 60;

            maintenanceTimer = new System.Timers.Timer(1000 * 60 * minutes);

            maintenanceTimer.Elapsed += new System.Timers.ElapsedEventHandler(maintenanceTimer_Elapsed);

            // Run maintenance every n number of minutes.
            maintenanceTimer.Interval = (1000 * 60 * minutes);

            maintenanceTimer.Enabled = true;

            eventLog1.WriteEntry("PlateletActive Service has initiated.");
        }
示例#34
0
        static void Main(string[] args)
        {
            Console.WriteLine("*********** Consumer ***********");

            IContainer myContainer = new StructureMap.Container();

            var bus = Bus.Initialize(config =>
            {
                config.SetContainer(myContainer);
                config.SetQueueName("PointToPoint.Consumer");
                config.SetHost(ConfigurationManager.AppSettings["RabbitMqHost"]);
                config.SetAuditingEnabled(false);
                config.SetNumberOfClients(20);
                config.SetLogger(new Logger());
            });

            bus.StartConsuming();

            Console.WriteLine("Connected");

            Console.ReadLine();

            bus.Dispose();
        }
示例#35
0
        public static void Main(string[] args)
        {
            LogConfig.Init();
            // add the framework services
            var services = new ServiceCollection();

            services.AddSingleton <IMapperFactory, TriviaMapperFactory>();

            // add StructureMap
            var container = new StructureMap.Container();

            container.Configure(config =>
            {
                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Program));
                    _.WithDefaultConventions();
                });
                // Populate the container using the service collection
                config.Populate(services);
            });

            var serviceProvider = container.GetInstance <IServiceProvider>();

            Application.Init();

            var operativeServices  = serviceProvider.GetService <IOperativeServices>();
            var backOfficeServices = serviceProvider.GetService <IBackOfficeServices>();

            TriviaApp   triviaApp   = new TriviaApp(operativeServices, backOfficeServices);
            LogInDialog logInDialog = new LogInDialog(triviaApp);

            logInDialog.Show();
            Application.Run();
        }
示例#36
0
 protected override IServiceLocatorAdapter GetAdapter()
 {
     container = new StructureMap.Container();
     return new StructureMapAdapter.StructureMapAdapter(container);
 }
示例#37
0
 private static IContainer InitContainer()
 {
     RRTracer.Trace("Initializing container");
     var initContainer = new StructureMap.Container();
     initContainer.Configure(x =>
                                 {
                                     x.For<IResourceType>().OnCreationForAll((c, r) =>
                                     {
                                         if (!r.FileName.Contains("RequestReduce"))
                                             throw new System.InvalidOperationException ("ResourceType file names must contain the string 'RequestReduce'");
                                     });
                                     x.For<IReducingQueue>().Singleton().Use<ReducingQueue>();
                                     x.For<IReductionRepository>().Singleton().Use<ReductionRepository>();
                                     x.For<IWuQuantizer>().Singleton().Use<WuQuantizer>();
                                     x.For<LocalDiskStore>().Singleton();
                                     x.For<DbDiskCache>().Singleton();
                                     x.For<SqlServerStore>().LifecycleIs(new RRHybridLifecycle()).Use<SqlServerStore>().
                                         Ctor<IStore>().Is(y => y.GetInstance<DbDiskCache>());
                                     x.For<IFileRepository>().Use<FileRepository>();
                                     x.For<IStore>().Use(y =>
                                                             {
                                                                 switch (
                                                                     y.GetInstance<IRRConfiguration>().
                                                                         ContentStore)
                                                                 {
                                                                     case
                                                                         Configuration.Store.
                                                                             SqlServerStore:
                                                                         return
                                                                             y.GetInstance
                                                                                 <SqlServerStore>();
                                                                     case
                                                                         Configuration.Store.
                                                                             LocalDiskStore:
                                                                     default:
                                                                         return
                                                                             y.GetInstance
                                                                                 <LocalDiskStore>();
                                                                 }
                                                             });
                                     x.For<HttpContextBase>().Use(() => HttpContext.Current == null ? null : new HttpContextWrapper(HttpContext.Current));
                                 });
     initContainer.Configure(x => x.Scan(y =>
                                             {
                                                 y.Assembly("RequestReduce");
                                                 y.ExcludeNamespace("RequestReduce.Utilities");
                                                 y.ExcludeNamespace("RequestReduce.Configuration");
                                                 y.ExcludeNamespace("RequestReduce.Store");
                                                 y.ExcludeNamespace("RequestReduce.ResourceTypes");
                                                 y.ExcludeType<IReductionRepository>();
                                                 y.ExcludeType<IReducingQueue>();
                                                 y.AddAllTypesOf<IReducer>();
                                                 y.WithDefaultConventions();
                                             }
                                      ));
     initContainer.Configure(x => x.Scan(y =>
                                             {
                                                 y.Assembly("RequestReduce");
                                                 y.IncludeNamespace("RequestReduce.Utilities");
                                                 y.IncludeNamespace("RequestReduce.Configuration");
                                                 y.IncludeNamespace("RequestReduce.ResourceTypes");
                                                 y.AddAllTypesOf<IResourceType>();
                                                 y.With(new SingletonConvention());
                                             }
                                      ));
     initContainer.Configure(
         x =>
         x.For<AbstractFilter>().Use(
             y =>
             HttpContext.Current == null
                 ? new ResponseFilter(null, Encoding.UTF8, y.GetInstance<IResponseTransformer>())
                 : new ResponseFilter(HttpContext.Current.Response.Filter, HttpContext.Current.Response.ContentEncoding, y.GetInstance<IResponseTransformer>())));
     return initContainer;
 }