Example #1
0
 public void CoreConfigExposesFileSource()
 {
     var factory = new ContainerFactory();
     var container = (CommonServiceLocatorAdapter)factory.GetCoreContainer(DotlessConfiguration.Default);
     var instance = container.GetInstance(typeof (ILessSource));
     Assert.IsInstanceOf<FileSource>(instance);
 }
Example #2
0
 public void HandlerUsesByDefaultAspServerPathProvider()
 {
     var factory = new ContainerFactory();
     var container = (CommonServiceLocatorAdapter) factory.GetContainer();
     var instance = container.GetInstance(typeof(ILessSource));
     Assert.IsInstanceOf<AspServerPathSource>(instance);
 }
 public void Test()
 {
     var container = new ContainerFactory()
         .WithTypesFromDefaultBinDirectory(false)
         .WithSettingsLoader(Activator.CreateInstance)
         .Build();
     Assert.That(container.Get<A>(), Is.Not.Null);
 }
        public void CanOverrideOptimization()
        {
            var config = new DotlessConfiguration { Optimization = 7 };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var parser = serviceLocator.GetInstance<Parser>();

            Assert.That(parser.Tokenizer.Optimization, Is.EqualTo(7));
        }
        public void CanPassCustomLessSource()
        {
            var config = new DotlessConfiguration { LessSource = typeof(DummyFileReader) };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var source = serviceLocator.GetInstance<IFileReader>();

            Assert.That(source, Is.TypeOf<DummyFileReader>());
        }
        public void CanPassCustomLogger()
        {
            var config = new DotlessConfiguration { Logger = typeof(DummyLogger) };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var logger = serviceLocator.GetInstance<ILogger>();

            Assert.That(logger, Is.TypeOf<DummyLogger>());
        }
        public void IfCacheOptionSetCacheIsInMemoryCache()
        {
            var config = new DotlessConfiguration { Web = false, CacheEnabled = true };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var cache = serviceLocator.GetInstance<ICache>();

            Assert.That(cache, Is.TypeOf<InMemoryCache>());
        }
 public void Test()
 {
     var referencedAssembly = AssemblyCompiler.Compile(referencedCode);
     var a1 = AssemblyCompiler.Compile(code1, referencedAssembly);
     var a2 = AssemblyCompiler.Compile(code2, referencedAssembly);
     var factory = new ContainerFactory()
         .WithTypesFromAssemblies(new[] {a1, a2})
         .WithAssembliesFilter(x => x.Name == a2.GetName().Name);
     using (var container = factory.Build())
     {
         var interfaceType = referencedAssembly.GetType("A1.ISomeInterface");
         Assert.That(container.Get(interfaceType).GetType().Name, Is.EqualTo("TestClass2"));
     }
 }
        public void CanOverrideLogLevel()
        {
            var config = new DotlessConfiguration { LogLevel = LogLevel.Info };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var logger = serviceLocator.GetInstance<ILogger>();

            Assert.That(logger, Is.TypeOf<ConsoleLogger>());

            var consoleLogger = (ConsoleLogger)logger;

            Assert.That(consoleLogger.Level, Is.EqualTo(LogLevel.Info));
        }
Example #10
0
        public void CachedCssResponseInstanceIsTransient()
        {
            var config = new DotlessConfiguration { Web = true };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var response1 = serviceLocator.GetInstance<IResponse>();
            var response2 = serviceLocator.GetInstance<IResponse>();

            Assert.That(response1, Is.Not.SameAs(response2));

            var http1 = (response1 as CachedCssResponse).Http;
            var http2 = (response2 as CachedCssResponse).Http;

            Assert.That(http1, Is.Not.SameAs(http2));
        }
        public void BuildExpression_ManuallyCompiledToDelegate_CanBeExecutedSuccessfully()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register <ICommand, ConcreteCommand>(new AsyncScopedLifestyle());

            // Creating the instance for type ICommand failed. The configuration is invalid.
            // The type ConcreteCommand is directly or indirectly depending on itself.
            // The cyclic graph contains the following types: ConcreteCommand.
            // Verification was triggered because Container.Options.EnableAutoVerification was enabled.
            // To prevent the container from being verified on first resolve, set the value to false.
            InstanceProducer producer   = container.GetRegistration(typeof(ICommand));
            Expression       expression = producer.BuildExpression();
            var factory = Expression.Lambda <Func <ICommand> >(expression).Compile();

            using (AsyncScopedLifestyle.BeginScope(container))
            {
                // Act
                factory();
            }
        }
        public void IEnumerableGetEnumerator_OnContainerControlledCollection_ReturnsACorrectEnumerator()
        {
            // Arrange
            List <object> pluginsCopy = new List <object>();

            var container = ContainerFactory.New();

            container.Collection.Register <IPlugin>(new[] { typeof(Plugin0), typeof(Plugin1), typeof(Plugin2) });

            var plugins = (IEnumerable)container.GetAllInstances <IPlugin>();

            // Act
            foreach (var plugin in plugins)
            {
                pluginsCopy.Add(plugin);
            }

            // Assert
            AssertThat.IsInstanceOfType(typeof(Plugin0), pluginsCopy[0]);
            AssertThat.IsInstanceOfType(typeof(Plugin1), pluginsCopy[1]);
            AssertThat.IsInstanceOfType(typeof(Plugin2), pluginsCopy[2]);
        }
Example #13
0
        public void GetInstance_SingletonThatGetsInjectedWithArrayWithTransients_ThrowsMismatchDetected()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Collection.Append <ILogger, ConsoleLogger>(Lifestyle.Transient);
            container.RegisterSingleton <ILogger, NoncaptivatingCompositeLogger <ILogger[]> >();

            // Act
            Action action = () => container.GetInstance <ILogger>();

            // Assert
            // No special communication about iterating during the collection: this can't be
            // detected as array is not a stream and can't be intercepted.
            AssertThat.ThrowsWithExceptionMessageDoesNotContain <ActivationException>(
                ResolvingServicesFromAnInjectedCollectionMessage,
                action);

            AssertThat.ThrowsWithExceptionMessageContains <ActivationException>(
                "lifestyle mismatch has been detected",
                action);
        }
Example #14
0
        [ActiveIssue("https://github.com/dotnet/runtime/issues/24240", TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
        public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            var exports = container.GetExports <Func <int, int, int>, ITrans_ExportableTest>("Add");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "add")
                {
                    Assert.Equal(3, export.Value(1, 2));
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.Equal(-1, export.Value(1, 2));
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
        public void RegisterManyForOpenGenericAssemblyIEnumerable_WithCallbackThatDoesNothing_DoesNotRegisterAnything()
        {
            // Arrange
            var container = ContainerFactory.New();

            BatchRegistrationCallback callback = (closedServiceType, implementations) =>
            {
                // Do nothing.
            };

            IEnumerable <Assembly> assemblies = new[] { Assembly.GetExecutingAssembly() };

            // Act
            container.RegisterManyForOpenGeneric(typeof(IService <,>), AccessibilityOption.PublicTypesOnly,
                                                 callback, assemblies);

            // Assert
            var registration = container.GetRegistration(typeof(IService <string, object>));

            Assert.IsNull(registration, "GetRegistration should result in null, because by supplying a delegate, the " +
                          "extension method does not do any registration itself.");
        }
        public void OptionalImportsOfExportValueTypesAreReboundToDefaultWhenExportIsRemoved()
        {
            var container = ContainerFactory.Create();
            var importer  = new OptionalExport();

            CompositionBatch batch = new CompositionBatch();

            batch.AddPart(importer);
            var key = batch.AddExportedValue("ValueType", 10);

            container.Compose(batch);

            Assert.Equal(1, importer.ValueTypeSetCount);
            Assert.Equal(10, importer.ValueType.Value);

            batch = new CompositionBatch();
            batch.RemovePart(key);
            container.Compose(batch);

            Assert.Equal(2, importer.ValueTypeSetCount);
            Assert.Null(importer.ValueType);
        }
        public void DelayImportValueComComponent()
        {
            CTaskScheduler scheduler = new CTaskScheduler();

            try
            {
                var container = ContainerFactory.Create();
                var importer  = new DelayImportComComponent();

                CompositionBatch batch = new CompositionBatch();
                batch.AddParts(importer);
                batch.AddExportedValue <ITaskScheduler>("TaskScheduler", (ITaskScheduler)scheduler);

                container.Compose(batch);

                Assert.Equal <object>(scheduler, importer.TaskScheduler.Value);
            }
            finally
            {
                Marshal.ReleaseComObject(scheduler);
            }
        }
Example #18
0
        public void Rejection_DefendPromisesLazily()
        {
            var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy));

            // Add the missing dependency for Needy
            container.ComposeParts(new NoImportPart());

            // This change should succeed since the component "Needy" hasn't been fully composed
            // and one way of satisfying its needs is as good ask another
            var export = container.GetExport <Needy>();

            // Cannot add another import because it would break existing promised compositions
            ExceptionAssert.Throws <ChangeRejectedException>(() =>
                                                             container.ComposeParts(new NoImportPart()));

            // Instansitate the object
            var needy = export.Value;

            // Cannot add another import because it would break existing compositions
            ExceptionAssert.Throws <ChangeRejectedException>(() =>
                                                             container.ComposeParts(new NoImportPart()));
        }
Example #19
0
        public void Import_VirtualPropertyOverrideWithDifferentContract_ShouldSucceed()
        {
            var container = ContainerFactory.Create();

            container.AddAndComposeExportedValue <int>("VirtualImport", 21);
            container.AddAndComposeExportedValue <int>("OverriddenImport", 42);

            var import = new ImportOnOverridenPropertyWithSameContract();

            container.SatisfyImportsOnce(import);

            // Import will get set twice because there are 2 imports on the same property.
            // We would really like to either elminate it getting set twice or error in this case
            // but we figure it is a rare enough corner case that it doesn't warrented the run time cost
            // and can be covered by an FxCop rule.

            Assert.Equal(2, import.ImportSetCount);

            // The derived most import should be discovered first and so it will get set first
            // and thus the value should be the base import which is 21.
            Assert.Equal(21, import.VirtualImport);
        }
Example #20
0
        public void Rejection_ExtensionLightUp_AddedViaBatch()
        {
            var container = ContainerFactory.CreateWithAttributedCatalog(
                typeof(MyImporter),
                typeof(Extension1),
                typeof(Extension2));

            var importer = container.GetExportedValue <MyImporter>();

            Assert.Equal(0, importer.Extensions.Length);

            container.ComposeExportedValue <int>("IExtension.IdValue", 10);

            Assert.Equal(1, importer.Extensions.Length);
            Assert.Equal(10, importer.Extensions[0].Id);

            container.ComposeExportedValue <int>("IExtension.IdValue2", 20);

            Assert.Equal(2, importer.Extensions.Length);
            Assert.Equal(10, importer.Extensions[0].Id);
            Assert.Equal(20, importer.Extensions[1].Id);
        }
Example #21
0
        private void SetupContiner()
        {
            var container = new ContainerFactory().GetEcardContainer();

            container.RegisterType <ISiteCssBuilder, DashboardItemSiteCssBuilder>("dashboarditem");
            container.RegisterType <IControllerFinder, AppDomainControllerFinder>(new ContainerControlledLifetimeManager());
            container.RegisterInstance <Database>(new Database("ecard"));
            container.RegisterType <DatabaseInstance>(new PerWebRequestLifetimeManager(Constants.KeyOfDatabaseInstance));
            container.RegisterType <IAuthenticateService, UserAndPasswordAuthenticateService>("password");
            container.RegisterType <IAuthenticateService, UserAndPasswordAndIKeyAuthenticateService>("ikeyandpassword");
            container.RegisterType <IPasswordService, NonePasswordService>("none");
            // delete for publish source code
            container.RegisterType <IPasswordService, SLE902rPasswordService>("sle902r");
            container.RegisterType <IPrinterService, NavAndPrintPrinterService>("navandprint");
            container.RegisterType <IPrinterService, DefaultPrinterService>("default");
            container.RegisterType <IPrinterService, AlertPrinterService>("alert");
            container.RegisterType <IPrinterService, NavPrinterService>("nav");

            EcardContext.Container = container;

            Application.Add("container", container);
        }
        public JsonResult GetFromDataSet([FromQuery] GetFromFileModel model)
        {
            var container = ContainerFactory.ReadFromFile($"{_dataSetDirectory}/{model.DataSet}");

            var watch = System.Diagnostics.Stopwatch.StartNew();

            container.GeneratePowerSet();
            container.SortSubsets();
            var subset = container.FindBestSubset();

            watch.Stop();
            long elapsedMs = watch.ElapsedMilliseconds;

            return(new JsonResult(new
            {
                Items = container.AllItems.Select(s => new
                {
                    s.Id,
                    s.Width,
                    s.Height,
                    s.Value
                }),
                ContainerWidth = container.Width,
                ContainerHeight = container.Height,
                SelectedSubset = subset.Items.Select(s => new
                {
                    s.Id,
                    s.Width,
                    s.Height,
                    s.Value,
                    s.UpperLeftCornerPoint,
                    s.DimensionsSwapped
                }),
                ExecutionTime = elapsedMs,
                TotalArea = subset.TotalArea,
                TotalValue = subset.TotalValue
            }));
        }
        public void Validate(ContainerFactory factory, ContainerRegistration registration, IList <string> errors)
        {
            var direct = registration as ContainerRegistrationDirect;

            if (direct == null)
            {
                return;
            }

            if (!registration.Binding.IsAssignableFrom(direct.Implementation))
            {
                errors.Add($"Registration resolving `{direct.Binding.GetRightFullName()}` "
                           + $"not assingable from `{direct.Implementation.GetRightFullName()}`");
                return;
            }

            var ctor = direct.Implementation
                       .GetConstructors()
                       .OrderBy(c => c.GetParameters()
                                .Count())
                       .First();

            var dependencies = ctor.GetParameters()
                               .Select(t => t.ParameterType);

            foreach (var dependency in dependencies)
            {
                var isRegistred = factory.Registrations
                                  .Any(t => t.Binding == dependency);

                if (!isRegistred)
                {
                    errors.Add($"Missing dependency `{dependency.GetRightFullName()}` "
                               + $"for implementation `{direct.Implementation.GetRightFullName()}` "
                               + $"and resolving type `{direct.Binding.GetRightFullName()}`");
                }
            }
        }
Example #24
0
        public void ValidMetadataTest()
        {
            var container          = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();

            batch.AddPart(new MyExporterWithValidMetadata());
            container.Compose(batch);

            var typeVi      = container.GetExport <MyExporterWithValidMetadata, IDictionary <string, object> >();
            var metadataFoo = typeVi.Metadata["foo"] as IList <string>;

            Assert.Equal(2, metadataFoo.Count());
            Assert.True(metadataFoo.Contains("bar1"), "The metadata collection should include value 'bar1'");
            Assert.True(metadataFoo.Contains("bar2"), "The metadata collection should include value 'bar2'");
            Assert.Equal("world", typeVi.Metadata["hello"]);
            Assert.Equal("GoodOneValue2", typeVi.Metadata["GoodOne2"]);

            var metadataAcme = typeVi.Metadata["acme"] as IList <object>;

            Assert.Equal(2, metadataAcme.Count());
            Assert.True(metadataAcme.Contains("acmebar"), "The metadata collection should include value 'bar'");
            Assert.True(metadataAcme.Contains(2.0), "The metadata collection should include value 2");

            var memberVi    = container.GetExport <Func <double>, IDictionary <string, object> >("ContractForValidMetadata");
            var metadataBar = memberVi.Metadata["bar"] as IList <string>;

            Assert.Equal(2, metadataBar.Count());
            Assert.True(metadataBar.Contains("foo1"), "The metadata collection should include value 'foo1'");
            Assert.True(metadataBar.Contains("foo2"), "The metadata collection should include value 'foo2'");
            Assert.Equal("hello", memberVi.Metadata["world"]);
            Assert.Equal("GoodOneValue2", memberVi.Metadata["GoodOne2"]);

            var metadataStuff = memberVi.Metadata["stuff"] as IList <object>;

            Assert.Equal(2, metadataAcme.Count());
            Assert.True(metadataStuff.Contains("acmebar"), "The metadata collection should include value 'acmebar'");
            Assert.True(metadataStuff.Contains(2.0), "The metadata collection should include value 2");
        }
        protected override void OnHandleIntent(Intent intent)
        {
            try
            {
                Console.WriteLine("Service Started");
                var containerFactory = new ContainerFactory();
                containerFactory.AddRegistrations(builder =>
                {
                    var androidRegistrations = new AndroidPlatformServicesRegistrator();
                    androidRegistrations.RegisterPlatformSpecificServices(builder);
                });

                var container    = containerFactory.Build();
                var synchronizer = container.Resolve <ISynchronizer>();

                var serverOnline = synchronizer.Synchronize().Result;
                Console.WriteLine($"Service Synchronization Finished - Result: {serverOnline}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #26
0
        public void CantDeleteSeveralKeysThatDontExist()
        {
            TestAllOptions((options, path) =>
            {
                var dictionary = new Dictionary <string, SecureString>
                {
                    { "key", ORIGINAL_VALUE.Secure() },
                    { "another key", ORIGINAL_VALUE2.Secure() }
                };

                var container = ContainerFactory.FromFile(path);
                container.Encrypt(dictionary, _password, options);

                var file = new FileInfo(path);
                Assert.IsTrue(file.Exists);

                var firstLength = file.Length;
                Assert.AreNotEqual(0, firstLength);

                container.Delete(new[] { "another third key", "another key" }, _password);
                Assert.Fail("Should not be able to Update a key that doesn't exist");
            });
        }
Example #27
0
        public void RegisterManyForOpenGeneric_WithNonInheritableType_ThrowsException()
        {
            // Arrange
            var container = ContainerFactory.New();

            var serviceType = typeof(IService <,>);
            var validType   = typeof(ServiceImpl <object, string>);
            var invalidType = typeof(List <int>);

            try
            {
                // Act
                container.RegisterManyForOpenGeneric(serviceType, validType, invalidType);

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (Exception ex)
            {
                AssertThat.StringContains("List<Int32>", ex.Message);
                AssertThat.StringContains("IService<TA, TB>", ex.Message);
            }
        }
Example #28
0
        public void CheckSides_Test()
        {
            //Arrange
            ShipContainer con = ContainerFactory.GenereateSpecificContainer(70000, ContainerMovement_V2.Objects.Enums.Types.ContainerTypes.Regular, 1)[0];

            Ship expected = ShipFactory.GenerateDefaultShip();

            expected.AddRegularContainer(con, ContainerMovement_V2.Objects.Enums.Types.Sides.Left);
            expected.AddRegularContainer(con, ContainerMovement_V2.Objects.Enums.Types.Sides.Right);
            expected.CheckBalance(false);

            Test_Dock.Ship.AddRegularContainer(con, ContainerMovement_V2.Objects.Enums.Types.Sides.Left);

            //Act
            Test_Dock.CheckSides(con);
            var actual = Test_Dock.Ship;

            actual.CheckBalance(false);

            //Assert
            Assert.AreEqual(expected.LeftWeight, actual.LeftWeight);
            Assert.AreEqual(expected.RightWeight, actual.RightWeight);
        }
Example #29
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var rootFrame = Window.Current.Content as Frame;

            if (rootFrame.CanGoBack)
            {
                // Show UI in title bar if opted-in and in-app backstack is not empty.
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                    AppViewBackButtonVisibility.Visible;
            }
            else
            {
                // Remove the UI from the title bar if in-app back stack is empty.
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                    AppViewBackButtonVisibility.Collapsed;
            }

            base.OnNavigatedTo(e);

            var container     = ContainerFactory.GetContainer();
            var facetsService = container.Resolve <IFacetsService>();
            await ViewModel.InitializeAsync(facetsService);
        }
Example #30
0
        public void CanMergeIntoAnEmptyFile()
        {
            TestAllOptions((options, path) =>
            {
                File.WriteAllText(path, "");

                var file = new FileInfo(path);
                Assert.IsTrue(file.Exists);
                Assert.AreEqual(0, file.Length);

                var dictionary = new Dictionary <string, SecureString>
                {
                    { "key", ORIGINAL_VALUE.Secure() },
                    { "another key", ORIGINAL_VALUE2.Secure() }
                };

                var container = ContainerFactory.FromFile(path);
                container.InsertOrUpdate(dictionary, _password, options);

                file.Refresh();
                Assert.AreNotEqual(0, file.Length);
            });
        }
        public void can_build_the_event_schema_objects_in_a_separted_schema()
        {
            var container = ContainerFactory.Configure(_ =>
                                                       // SAMPLE: override_schema_name_event_store
                                                       _.Events.DatabaseSchemaName = "event_store"
                                                       // ENDSAMPLE
                                                       );

            container.GetInstance <DocumentCleaner>().CompletelyRemoveAll();

            var schema = container.GetInstance <IDocumentSchema>();

            schema.EnsureStorageExists(typeof(EventStream));

            var schemaFunctionNames = schema.DbObjects.SchemaFunctionNames();

            schemaFunctionNames.ShouldContain("event_store.mt_append_event");

            var schemaTableNames = schema.DbObjects.SchemaTables();

            schemaTableNames.ShouldContain("event_store.mt_streams");
            schemaTableNames.ShouldContain("event_store.mt_events");
        }
Example #32
0
        public void BuildExpression_WithHybridLifestyleAndRegisteredDelegate_BuildsExpectedExpression()
        {
            // Arrange
            var hybrid = Lifestyle.CreateHybrid(() => false, Lifestyle.Transient, Lifestyle.Singleton);

            var container = ContainerFactory.New();

            container.Register <IUserRepository>(() => new SqlUserRepository(), hybrid);

            var registration = container.GetRegistration(typeof(IUserRepository));

            // Act
            var expression = registration.BuildExpression().ToString();

            // Assert
            Assert.IsTrue(expression.StartsWith(
                              "IIF(Invoke(value(System.Func`1[System.Boolean])), Convert("),
                          "Actual: " + expression);

            Assert.IsTrue(expression.EndsWith(
                              "Convert(value(SimpleInjector.Tests.Unit.SqlUserRepository)))"),
                          "Actual: " + expression);
        }
Example #33
0
        public override void OnReceive(Context context, Intent intent)
        {
            Console.WriteLine($"Boot receiver started. Action: {intent.Action}");
            var containerFactory = new ContainerFactory();

            containerFactory.AddRegistrations(builder =>
            {
                var androidRegistrations = new AndroidPlatformServicesRegistrator();
                androidRegistrations.RegisterPlatformSpecificServices(builder);
            });

            var container            = containerFactory.Build();
            var configurationManager = container.Resolve <IMobileConfigurationReader>();

            if (configurationManager.GetConfiguration().AlreadyInitialized)
            {
                if (configurationManager.GetConfiguration().ApplicationMode == ApplicationMode.Client)
                {
                    var synchronizer = container.Resolve <ISynchronizationServiceManager>();
                    synchronizer.StartSynchronizationService();
                }
            }
        }
Example #34
0
        public void can_build_the_mt_stream_schema_objects_in_different_database_schema()
        {
            var container = ContainerFactory.Configure(options => options.DatabaseSchemaName = "other");

            container.GetInstance <DocumentCleaner>().CompletelyRemoveAll();

            var schema = container.GetInstance <IDocumentSchema>();

            schema.EnsureStorageExists(typeof(EventStream));

            var store = container.GetInstance <IDocumentStore>();

            store.EventStore.InitializeEventStoreInDatabase(true);

            var schemaFunctionNames = schema.DbObjects.SchemaFunctionNames();

            schemaFunctionNames.ShouldContain("other.mt_append_event");

            var schemaTableNames = schema.DbObjects.SchemaTables();

            schemaTableNames.ShouldContain("other.mt_streams");
            schemaTableNames.ShouldContain("other.mt_events");
        }
Example #35
0
        public void TestInterfaces()
        {
            var container = ContainerFactory.CreateWithAttributedCatalog(
                typeof(MyToolbarPlugin));

            var app = new object();

            container.AddAndComposeExportedValue <object>("Application", app);

            var toolbar = new object();

            container.AddAndComposeExportedValue <object>("ToolBar", toolbar);

            var export = container.GetExportedValue <IToolbarPlugin>();

            Assert.Equal(app, export.Application);
            Assert.Equal(toolbar, export.ToolBar);
            Assert.Equal("MyToolbarPlugin", export.Name);

            var pluginNames = container.GetExportedValues <string>("ApplicationPluginNames");

            Assert.Equal(1, pluginNames.Count());
        }
Example #36
0
        public void CantInsertAKeyTwice()
        {
            TestAllOptions((options, path) =>
            {
                var dictionary = new Dictionary <string, SecureString>
                {
                    { "key", ORIGINAL_VALUE.Secure() },
                    { "another key", ORIGINAL_VALUE2.Secure() }
                };

                var container = ContainerFactory.FromFile(path);
                container.Encrypt(dictionary, _password, options);

                var file = new FileInfo(path);
                Assert.IsTrue(file.Exists);

                var firstLength = file.Length;
                Assert.AreNotEqual(0, firstLength);

                container.Insert("another key", ORIGINAL_VALUE3.Secure(), _password);
                Assert.Fail("Should not be able to insert a key twice");
            });
        }
        public void Can_Create_Parallelogram_Container()
        {
            var cont = ContainerFactory.CreateParallelogram(60, 6, 10, TrianglePattern.TwoPerColumn);

            Assert.True(cont.Rows == cont.Columns && cont.Rows == 6);
            var loc = new TriangleLocation(4, 4);
            var t   = cont.GetTriangleAt(loc);

            Assert.False(t.IsEmpty);
            var tAddr = t.Location.Address;

            Assert.Equal("E5", tAddr);
            loc = cont.GetTriangleLocation(t);
            Assert.True(loc.IsValid);
            Assert.Equal("E5", loc.Address);

            var sz         = cont.Size;
            var testHeight = Math.Round(Math.Sin(0.33333333) * 60, 4);
            var testWidth  = Math.Round(60 * (1 + Math.Cos(0.33333333)), 4);

            Assert.Equal <double>(testHeight, Math.Round(sz.Height, 4));
            Assert.Equal <double>(testWidth, Math.Round(sz.Width, 4));
        }
Example #38
0
        public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
        {
            int importSatisfationCount = 0;
            var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
            var importer2 = new MyEventDrivenFullComposedNotifyImporter2();

            Action <object, EventArgs> verificationAction = (object sender, EventArgs e) =>
            {
                Assert.True(importer1.AreAllImportsFullyComposed);
                Assert.True(importer2.AreAllImportsFullyComposed);
                ++importSatisfationCount;
            };

            importer1.ImportsSatisfied += new EventHandler(verificationAction);
            importer2.ImportsSatisfied += new EventHandler(verificationAction);

            // importer1 added first
            var batch = new CompositionBatch();

            batch.AddParts(importer1, importer2);

            var container = ContainerFactory.Create();

            container.ComposeExportedValue <ICompositionService>(container);
            container.Compose(batch);
            Assert.Equal(2, importSatisfationCount);

            // importer2 added first
            importSatisfationCount = 0;
            batch = new CompositionBatch();
            batch.AddParts(importer2, importer1);

            container = ContainerFactory.Create();
            container.ComposeExportedValue <ICompositionService>(container);
            container.Compose(batch);
            Assert.Equal(2, importSatisfationCount);
        }
Example #39
0
        public void GetInstance_Always_CallsTheDelegate()
        {
            // Arrange
            int  callCount = 0;
            bool pickLeft  = true;

            Func <bool> predicate = () =>
            {
                // This predicate should be called on each resolve.
                // In a sense the predicate itself is transient.
                callCount++;
                return(pickLeft);
            };

            var hybrid = Lifestyle.CreateHybrid(predicate, Lifestyle.Transient, Lifestyle.Singleton);

            var container = ContainerFactory.New();

            container.Register <IUserRepository, SqlUserRepository>(hybrid);

            // Act
            var provider1 = container.GetInstance <IUserRepository>();
            var provider2 = container.GetInstance <IUserRepository>();

            pickLeft = false;

            var provider3 = container.GetInstance <IUserRepository>();
            var provider4 = container.GetInstance <IUserRepository>();

            // Assert
            Assert.AreEqual(4, callCount);
            Assert.IsFalse(object.ReferenceEquals(provider1, provider2),
                           "When the predicate returns true, transient instances should be returned.");
            Assert.IsFalse(object.ReferenceEquals(provider2, provider3), "This is really weird.");
            Assert.IsTrue(object.ReferenceEquals(provider3, provider4),
                          "When the predicate returns false, a singleton instance should be returned.");
        }
Example #40
0
        public void will_build_the_new_table_if_the_configured_table_does_not_match_the_existing_table_on_other_schema()
        {
            TableDefinition table1;
            TableDefinition table2;

            using (var container = ContainerFactory.OnOtherDatabaseSchema())
            {
                var store = container.GetInstance <IDocumentStore>();

                store.Advanced.Clean.CompletelyRemoveAll();

                store.Schema.StorageFor(typeof(User));

                store.Schema.DbObjects.DocumentTables().ShouldContain("other.mt_doc_user");

                table1 = store.Schema.TableSchema(typeof(User));
                table1.Columns.ShouldNotContain(x => x.Name == "user_name");
            }

            using (var container = ContainerFactory.OnOtherDatabaseSchema())
            {
                var store = container.GetInstance <IDocumentStore>();

                store.Schema.MappingFor(typeof(User)).As <DocumentMapping>().DuplicateField("UserName");

                store.Schema.StorageFor(typeof(User));

                store.Schema.DbObjects.DocumentTables().ShouldContain("other.mt_doc_user");

                table2 = store.Schema.TableSchema(typeof(User));
            }

            table2.ShouldNotBe(table1);

            table2.Column("user_name").ShouldNotBeNull();
        }
 public void Test()
 {
     var f = new ContainerFactory()
         .WithTypesFromDefaultBinDirectory(false)
         .WithSettingsLoader(Activator.CreateInstance);
     using (var c1 = f.WithConfigurator(b => b.BindDependency<A>("parameter", 1)).Build())
         Assert.That(c1.Get<A>().parameter, Is.EqualTo(1));
     using (var c2 = f.WithConfigurator(b => { }).Build())
         Assert.That(c2.Get<A>().parameter, Is.EqualTo(-1));
 }
 public void Test()
 {
     var assembly = AssemblyCompiler.Compile(testCode);
     File.WriteAllText(configFileName, "A.parameter->11");
     var factory = new ContainerFactory()
         .WithAssembliesFilter(x => x.Name.StartsWith("tmp_"))
         .WithConfigFile(configFileName)
         .WithTypesFromAssemblies(new[] { assembly });
     var e = Assert.Throws<SimpleContainerException>(() => factory.Build());
     Assert.That(e.Message, Is.EqualTo("for name [A] more than one type found [A1.A], [A2.A]"));
 }
Example #43
0
        public void HandlerImplInstanceIsTransient()
        {
            var config = new DotlessConfiguration { Web = true };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var handler1 = serviceLocator.GetInstance<HandlerImpl>();
            var handler2 = serviceLocator.GetInstance<HandlerImpl>();

            Assert.That(handler1, Is.Not.SameAs(handler2));

            var http1 = handler1.Http;
            var http2 = handler2.Http;

            Assert.That(http1, Is.Not.SameAs(http2));

            var response1 = handler1.Response;
            var response2 = handler2.Response;

            Assert.That(response1, Is.Not.SameAs(response2));

            var engine1 = handler1.Engine;
            var engine2 = handler2.Engine;

            Assert.That(engine1, Is.Not.SameAs(engine2));
        }
Example #44
0
        public void HttpInstanceIsTransient()
        {
            var config = new DotlessConfiguration { Web = true };

            var serviceLocator = new ContainerFactory().GetContainer(config);

            var http1 = serviceLocator.GetInstance<IHttp>();
            var http2 = serviceLocator.GetInstance<IHttp>();

            Assert.That(http1, Is.Not.SameAs(http2));
        }
 public void Test()
 {
     var referencedAssembly = AssemblyCompiler.Compile(referencedCode);
     var assembly = AssemblyCompiler.Compile(code, referencedAssembly);
     var factory = new ContainerFactory().WithTypesFromAssemblies(new[] {assembly});
     using (var container = factory.Build())
     {
         var interfaceType = referencedAssembly.GetType("A1.ISomeInterface");
         Assert.That(container.Get(interfaceType).GetType().Name, Is.EqualTo("SomeInterfaceImpl"));
     }
 }
Example #46
0
        public void IfWebAndCacheOptionsSetCacheIsHttpCache()
        {
            var config = new DotlessConfiguration { Web = true, CacheEnabled = true };

            var serviceLocator = new ContainerFactory().GetLessContainer(config);

            var cache = serviceLocator.GetInstance<ICache>();

            Assert.That(cache, Is.TypeOf<HttpCache>());
        }