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);
        }
Example #2
0
        // 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>());
        }
Example #3
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);
        }
        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);
            });
        }
Example #5
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);
        }
        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));
        }
        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);
        }
Example #9
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");
        }
 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);
     }
 }
Example #12
0
        // 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>());
        }
Example #13
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>());
        }
Example #14
0
        public static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            tim.Stop();

            // Se emula un incendio y se manda los datos a la cola de mensajes.

            IncendioObjt inc = ObjtIncencioRandomGenerator.GetRandomObjetc();

            //Para transimitr el mensaje al front se usa inyección de dependecncias
            var mess = container.GetInstance <IMessaging>();

            mess.PublishMessage(inc.ConcatObjt, "IncendioEmulatorQueue");

            tim.Start();
        }
        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>());
        }
        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>());
        }
        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.");
        }
Example #19
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>());
        }
Example #20
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();
        }
Example #21
0
 public object Resolve(Type type)
 {
     return(_container.GetInstance(type));
 }
Example #22
0
 public T GetInstanceAs <T>()
 {
     return((T)_container.GetInstance(_pluginType));
 }
Example #23
0
 public T GetInstance <T>()
 {
     return(_container.GetInstance <T>());
 }
        public override void Run()
        {
            var webApp = container.GetInstance <IWebService>();

            webApp.Execute();
        }
Example #25
0
 // Once the user is successfully authenticated, add additional
 // claims that are specific to ODT and user context
 private Task TokenValidated(TokenValidatedContext n)
 {  
     n.Ticket.Principal.AddIdentity(container.GetInstance<IUserHelper>().GetByUserName( n.Ticket.Principal.Identity.Name).Identities.FirstOrDefault());            
     n.Properties.RedirectUri = "/Account/Gatekeeper";
     return Task.FromResult(0);
 }
Example #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<IConfigurationRoot>(Configuration);
            services.Configure<AppSettings>(Configuration.GetSection("Application"));
            var appSettings = Configuration.Get<AppSettings>("Application");


            // Add framework services.
            services.AddMvc();    
            //services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache

            // Using Redis as Memory cache
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = appSettings.Redis.Url;
                options.InstanceName = appSettings.Redis.InstanceName;
                options.ResolveDns();
            });
            services.AddSession();
            services.AddSignalR();

            // Predefine set of policies        
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ADMIN", policy => {
                    policy.RequireClaim("admin");
                });

                 options.AddPolicy("READ", policy => {
                    policy.RequireClaim("read");
                });

                options.AddPolicy("WRITE", policy => {
                    policy.RequireClaim("write");
                });

                options.AddPolicy("GET", policy => {
                    policy.RequireClaim("get");
                });

                options.AddPolicy("POST", policy => {
                    policy.RequireClaim("post");
                });

                 options.AddPolicy("DELETE", policy => {
                    policy.RequireClaim("delete");
                });
            });

            // Add Authentication services.
            services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

            // Initialize container            
            container = new Container();
            container.Configure(c =>
            {
                Serilog.ILogger appLogger = new LoggerConfiguration()
                     .WriteTo.Logzio(appSettings.LogzIO.AuthToken,
                     application: appSettings.LogzIO.Application,
                     reporterType: appSettings.LogzIO.ReporterType,
                     environment: appSettings.LogzIO.Environment)
                     .CreateLogger();
                c.For<IApplicationContext>().Use<HttpAPIContext>();
                c.ForSingletonOf<AppSettings>().Use(appSettings);
                c.ForSingletonOf<Serilog.ILogger>().Use(appLogger);
            });

            services.InitializeAutoMapper();


            // Resolve container 
            DependencyResolver.RegisterResolver(new StructureMapIOCContainer(container)).RegisterImplmentation();
            container.Populate(services);

            return container.GetInstance<IServiceProvider>();
        }