Beispiel #1
0
    public static (IContainerInfo containerInfo, IConfiguration configuration) LoadConfigurationFile(DiImplementationType diImplementationType,
                                                                                                     [NotNull] string configurationRelativePath,
                                                                                                     [CanBeNull] IDiModule[] additionalModulesToLoad = null,
                                                                                                     [CanBeNull] Action <XmlDocument> modifyConfigurationFileOnLoad = null)
    {
        TestsHelper.SetupLogger();

        var ioCConfigurator = new DiContainerBuilder.DiContainerBuilder()
                              .StartFileBasedDi(
            new FileBasedConfigurationParameters(
                new FileBasedConfigurationFileContentsProvider(Path.Combine(Helpers.TestsEntryAssemblyFolder, configurationRelativePath)),
                Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
        {
            ConfigurationFileXmlDocumentLoaded = (sender, e) =>
            {
                Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));

                // Lets explicitly set the DiManager to Autofac. Since we are going to test failure, the Di manager implementation does not matter.
                // However, this will give us predictability on what modules will be enabled.
                e.XmlDocument.SelectElement("/iocConfiguration/diManagers").SetAttributeValue(ConfigurationFileAttributeNames.ActiveDiManagerName, diImplementationType.ToString());
                modifyConfigurationFileOnLoad?.Invoke(e.XmlDocument);
            },
            AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() },
        }, out _)
                              .WithoutPresetDiContainer();

        if (additionalModulesToLoad?.Length > 0)
        {
            ioCConfigurator.AddAdditionalDiModules(additionalModulesToLoad);
        }

        var containerInfo = ioCConfigurator.RegisterModules().Start();

        return(containerInfo, containerInfo.DiContainer.Resolve <IConfiguration>());
    }
Beispiel #2
0
        public void TestFileBasedDiContainerBuilderWithDiContainerProvided(DiImplementationType diImplementationType, bool isLoggerNotSetTest)
        {
            RuntTests(isLoggerNotSetTest, () =>
            {
                var diContainer = CreateDiContainer(diImplementationType);

                var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();

                using (var containerInfo = diContainerBuilder.StartFileBasedDi(
                           new FileBasedConfigurationParameters(
                               new FileBasedConfigurationFileContentsProvider(
                                   Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                               Helpers.TestsEntryAssemblyFolder,
                               new LoadedAssembliesForTests())
                {
                    ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                    {
                        Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));
                        ConfigurationFileXmlDocumentLoadedEventHandler(diImplementationType, e);
                    },
                    AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() }
                }, out _)
                                           .WithDiContainer(diContainer)
                                           .AddAdditionalDiModules(new DiModule1())
                                           .AddNativeModules(CreateNativeModule(diImplementationType))
                                           .RegisterModules()
                                           .Start())
                {
                    Assert.AreSame(diContainer, containerInfo.DiContainer);

                    ValidateFileBasedDiContainer(diImplementationType, containerInfo.DiContainer);
                }
            });
        }
Beispiel #3
0
    public void FileBasedConfigurationParameters_AdditionalReferencedAssemblies_Demo()
    {
        TestsHelper.SetupLogger();

        var fileBasedConfigurationParameters = new FileBasedConfigurationParameters(
            new FileBasedConfigurationFileContentsProvider(
                Path.Combine(Helpers.TestsEntryAssemblyFolder, @"DocumentationTests\AutoServiceCustom\DemoIoCConfiguration_autoServiceCustom.xml")),
            Helpers.TestsEntryAssemblyFolder,
            // LoadedAssembliesForTests is an implementation of ILoadedAssemblies that has a method
            // "IEnumerable<Assembly> GetAssemblies()" that returns list of assemblies to add as references to
            // generate dynamic assembly.
            new LoadedAssembliesForTests())
        {
            AdditionalReferencedAssemblies = new []
            {
                // List additional assemblies that should be added to dynamically generated assembly as references
                Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly1.dll"),
                Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly2.dll")
            },
            AttributeValueTransformers         = new[] { new FileFolderPathAttributeValueTransformer() },
            ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                                                 Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"))
        };

        var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                            .StartFileBasedDi(fileBasedConfigurationParameters, out _)
                            .WithoutPresetDiContainer()
                            .RegisterModules().Start();

        var autoImplementedInterfaceInstance = containerInfo.DiContainer.Resolve <IoC.Configuration.Tests.DocumentationTests.AutoServiceCustom.ISimpleAutoImplementedInterface1>();

        Assert.AreEqual(10, autoImplementedInterfaceInstance.GetValue());
    }
Beispiel #4
0
        public void ResolveBindings()
        {
            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder().StartFileBasedDi(
                       new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(
                                                                Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                                                            Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AttributeValueTransformers = new IAttributeValueTransformer [] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    // Replace some elements in e.XmlDocument if needed,
                    // before the configuration is loaded.
                }
            }, out _)
                                       .WithoutPresetDiContainer()
                                       .RegisterModules()
                                       .Start())
            {
                var diContainer = containerInfo.DiContainer;

                LifetimeScopeResolutionExample(diContainer);
                SingletonScopeResolutionExample(diContainer);
                TransientScopeResolutionExample(diContainer);

                ResolvingATypeWithMultipleBindings(diContainer);
            }
        }
Beispiel #5
0
        private void TestCodeBasedIoCBuilderWithNoDiContainerProvided(string diManagerClassFullName,
                                                                      string diManagerClassAssemblyFilePath,
                                                                      ParameterInfo[] diManagerConstructorParameters,
                                                                      params string[] assemblyProbingPaths)
        {
            var ioCBuilder = new DiContainerBuilder.DiContainerBuilder();

            ioCBuilder.StartCodeBasedDi(diManagerClassFullName, diManagerClassAssemblyFilePath, diManagerConstructorParameters, Helpers.TestsEntryAssemblyFolder, assemblyProbingPaths);
        }
Beispiel #6
0
        protected static void ClassInitializeCommon(DiImplementationType diImplementationType, Action <ConfigurationFileXmlDocumentLoadedEventArgs> configurationFileXmlDocumentLoadedEventHandler)
        {
            // JetBrains.ReSharper.TestRunner.Merged
            TestsHelper.SetupLogger();
            Log4Tests.LogLevel = LogLevel.Debug;

            _diImplementationType = diImplementationType;

            _mainLifeTimeScopeTerminatedExecuted = false;
            var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();


            var fileBasedConfigurationParameters = new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(
                                                                                            Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                                                                                        Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AttributeValueTransformers         = new[] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));

                    Helpers.ReplaceActiveDiManagerInConfigurationFile(e.XmlDocument, _diImplementationType);
                    configurationFileXmlDocumentLoadedEventHandler?.Invoke(e);
                }
            };

            _containerInfo = diContainerBuilder.StartFileBasedDi(
                fileBasedConfigurationParameters, out _)
                             .WithoutPresetDiContainer()
                             .AddAdditionalDiModules(new TestModule2())
                             .RegisterModules()
                             .Start();

            _diContainer = _containerInfo.DiContainer;

            var injectedStartupActionsHelper = _diContainer.Resolve <ClassToTestServicesInjection <IStartupAction> >();

            _startupActionsToTest = injectedStartupActionsHelper.Implementations.Where(x => x is IStartupActionState &&
                                                                                       new[]
            {
                "DynamicallyLoadedAssembly1.Implementations.StartupAction1",
                "DynamicallyLoadedAssembly1.Implementations.StartupAction2"
            }
                                                                                       .Contains(x.GetType().FullName)).ToList();

            var injectedPluginsHelper = _diContainer.Resolve <ClassToTestServicesInjection <IPlugin> >();

            _pluginsToTest = injectedPluginsHelper.Implementations.Where(x => x is IPluginState &&
                                                                         new[]
            {
                "TestPluginAssembly1.Implementations.Plugin1",
                "TestPluginAssembly2.Implementations.Plugin2"
            }
                                                                         .Contains(x.GetType().FullName)).ToList();

            _diContainer.MainLifeTimeScope.LifeTimeScopeTerminated += (sender, e) => { _mainLifeTimeScopeTerminatedExecuted = true; };
        }
Beispiel #7
0
        public void TestCodeBasedDiContainerBuilder(DiImplementationType diImplementationType,
                                                    IEnumerable <string> assemblyProbingPaths,
                                                    bool isPresetDiContainer)
        {
            var          diImplementationInfo = DiManagerHelpers.GetDiImplementationInfo(diImplementationType);
            IDiContainer presetDiContainer    = null;

            var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();

            var diContainerConfigurator = diContainerBuilder.StartCodeBasedDi(diImplementationInfo.DiManagerClassName,
                                                                              diImplementationInfo.DiManagerAssemblyPath,
                                                                              new ParameterInfo[0], Helpers.TestsEntryAssemblyFolder,
                                                                              assemblyProbingPaths.ToArray());

            ICodeBasedDiModulesConfigurator diModulesConfigurator = null;

            if (isPresetDiContainer)
            {
                presetDiContainer     = CreateDiContainer(diImplementationType);
                diModulesConfigurator = diContainerConfigurator.WithDiContainer(presetDiContainer);
            }
            else
            {
                diModulesConfigurator = diContainerConfigurator.WithoutPresetDiContainer();
            }

            string nativeModuleClassName             = null;
            var    nativeModuleClassAssemblyFilePath = Path.Combine(DiManagerHelpers.DynamicallyLoadedDllsFolder, "TestProjects.Modules.dll");

            switch (diImplementationType)
            {
            case DiImplementationType.Autofac:
                nativeModuleClassName = "Modules.Autofac.AutofacModule1";
                break;

            case DiImplementationType.Ninject:
                nativeModuleClassName = "Modules.Ninject.NinjectModule1";
                break;
            }

            using (var containerInfo = diModulesConfigurator
                                       .AddNativeModule(nativeModuleClassName, nativeModuleClassAssemblyFilePath,
                                                        new[] { new ParameterInfo(typeof(int), 18) })
                                       .AddDiModules(new DiModule1())
                                       .RegisterModules()
                                       .Start())
            {
                if (isPresetDiContainer)
                {
                    Assert.AreSame(presetDiContainer, containerInfo.DiContainer);
                }

                ValidateDiContainer(diImplementationType, containerInfo.DiContainer);
            }
        }
        public void LoadFromModules()
        {
            var diImplementationInfo = DiManagerHelpers.GetDiImplementationInfo(DiImplementationType.Autofac);

            var assemblyProbingPaths = new[]
            {
                DiManagerHelpers.ThirdPartyLibsFolder,
                diImplementationInfo.DiManagerFolder
            };

            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()

                                       // Class IoC.Configuration.DiContainerBuilder.DiContainerBuilder has two overloaded methods StartCodeBasedDi(...)
                                       // DiContainerBuilder.StartCodeBasedDi(IoC.Configuration.DiContainer.IDiManager diManager,...) and
                                       // DiContainerBuilder.StartCodeBasedDi(string diManagerClassFullName, string diManagerClassAssemblyFilePath,...).
                                       // if the project references the library with implementation of IoC.Configuration.DiContainer.IDiManager,
                                       // the first one can be used. Otherwise the second overloaded method can be used, in which case reflection will be used to
                                       // create an instance of IoC.Configuration.DiContainer.IDiManager.
                                       .StartCodeBasedDi("IoC.Configuration.Autofac.AutofacDiManager",
                                                         Path.Combine(Helpers.GetTestFilesFolderPath(),
                                                                      @"ContainerImplementations\Autofac\IoC.Configuration.Autofac.dll"),
                                                         Array.Empty <ParameterInfo>(), Helpers.TestsEntryAssemblyFolder, assemblyProbingPaths)
                                       // Note, most of the time we will need to call method WithoutPresetDiContainer().
                                       // However, in some cases, we might need to create an instance of IoC.Configuration.DiContainer.IDiContainer,
                                       // and call the method WithDiContainer(IoC.Configuration.DiContainer.IDiContainer diContainer) instead.
                                       // This might be necessary when using the IoC.Configuration to configure dependency injection in
                                       // ASP.NET Core projects.
                                       // An example implementation of IDIContainer is IoC.Configuration.Autofac.AutofacDiContainer in
                                       // Nuget package IoC.Configuration.Autofac.
                                       .WithoutPresetDiContainer()

                                       // The methods AddDiModules(params IDiModule[] diModules),
                                       // AddNativeModules(params object[] nativeModules), and
                                       // AddNativeModules(string nativeModuleClassFullName, string nativeModuleClassAssemblyFilePath, ...)
                                       // are used to load IoC.Configuration modules (instances of IoC.Configuration.DiContainer.IDiModule), as well
                                       // as native (e.g, Ninject or Autofac) modules.
                                       // Also, these three methods can be called multiple times in any order.
                                       .AddDiModules(new TestDiModule())
                                       .AddNativeModule("Modules.Autofac.AutofacModule1",
                                                        Path.Combine(Helpers.GetTestFilesFolderPath(),
                                                                     @"DynamicallyLoadedDlls\TestProjects.Modules.dll"),
                                                        new ParameterInfo[] { new ParameterInfo(typeof(int), 5) })

                                       .RegisterModules()
                                       .Start())
            {
                var diContainer = containerInfo.DiContainer;

                // Once the configuration is loaded, resolve types using IoC.Configuration.DiContainer.IDiContainer
                // Note, interface IoC.Configuration.DiContainerBuilder.IContainerInfo extends System.IDisposable,
                // and should be disposed, to make sure all the resources are properly disposed of.
                var resolvedInstance = containerInfo.DiContainer.Resolve <IInterface2>();
            }
        }
 public void TestSettings()
 {
     using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                .StartFileBasedDi(new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(
                                                                                           Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                                                                                       Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
     {
         AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() }
     }, out _)
                                .WithoutPresetDiContainer()
                                .AddAdditionalDiModules(new TestDiModule())
                                .RegisterModules()
                                .Start())
     {
         Assert.IsNotNull(containerInfo.DiContainer.Resolve <TestInjectedSettings>());
     }
 }
Beispiel #10
0
        public void FileConfigurationExample1()
        {
            TestsSharedLibrary.TestsHelper.SetupLogger();

            var configurationFileContentsProvider = new FileBasedConfigurationFileContentsProvider(
                Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml"));

            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                       .StartFileBasedDi(
                       new FileBasedConfigurationParameters(configurationFileContentsProvider,
                                                            Helpers.TestsEntryAssemblyFolder,
                                                            new LoadedAssembliesForTests())
            {
                AdditionalReferencedAssemblies = new []
                {
                    // List additional assemblies that should be added to dynamically generated assembly as references
                    Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly1.dll"),
                    Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly2.dll")
                },
                AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    // Replace some elements in e.XmlDocument if needed,
                    // before the configuration is loaded.
                    Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));
                }
            }, out _)
                                       .WithoutPresetDiContainer()
                                       .AddAdditionalDiModules(new TestDiModule())
                                       .RegisterModules()
                                       .Start())
            {
                var container = containerInfo.DiContainer;

                Assert.IsNotNull(containerInfo.DiContainer.Resolve <IInterface6>());

                var settings = container.Resolve <ISettings>();
                Assert.AreEqual(155.7, settings.GetSettingValueOrThrow <double>("MaxCharge"));

                var pluginRepository = container.Resolve <IPluginDataRepository>();

                var pluginData = pluginRepository.GetPluginData("Plugin1");
                Assert.AreEqual(38, pluginData.Settings.GetSettingValueOrThrow <long>("Int64Setting1"));
            }
        }
        protected static IContainerInfo CreateCodeBasedContainerInfo(DiImplementationType diImplementationType)
        {
            var diImplementationInfo = DiManagerHelpers.GetDiImplementationInfo(diImplementationType);

            var assemblyProbingPaths = new[]
            {
                DiManagerHelpers.ThirdPartyLibsFolder, diImplementationInfo.DiManagerFolder
            };

            var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();

            return(diContainerBuilder.StartCodeBasedDi(diImplementationInfo.DiManagerClassName,
                                                       diImplementationInfo.DiManagerAssemblyPath,
                                                       new ParameterInfo[0], Helpers.TestsEntryAssemblyFolder, assemblyProbingPaths)
                   .WithoutPresetDiContainer()
                   .AddDiModules(new TestDiModule(), new TestModule2())
                   .RegisterModules().Start());
        }
    public void SuccessfulTransformationOfPathAttributeValues()
    {
        using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                   .StartFileBasedDi(new FileBasedConfigurationParameters(CreateFileBasedConfigurationFileContentsProvider(),
                                                                                          Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
        {
            // Commenting out the next line will result in failing to load the configuration
            // because of values of path attributes (e.g., path="TestFiles\AutogeneratedDlls\attributeValueTransformers",
            // pluginsDirPath = "TestFiles\PluginDlls", path="TestFiles\ThirdPartyLibs", etc).
            AttributeValueTransformers = new [] { new FileFolderPathAttributeValueTransformer() },

            ConfigurationFileXmlDocumentLoaded = ConfigurationFileXmlDocumentLoadedEventHandler
        }, out _)
                                   .WithoutPresetDiContainer()
                                   .RegisterModules()
                                   .Start())
        {
            Assert.IsNotNull(containerInfo.DiContainer.Resolve <SharedServices.Interfaces.IInterface1>());
        }
    }
        protected static IContainerInfo CreateFileConfigurationBasedContainerInfo(DiImplementationType diImplementationType)
        {
            var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();

            return(diContainerBuilder.StartFileBasedDi(
                       new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(
                                                                Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration2.xml")),
                                                            Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));
                    Helpers.ReplaceActiveDiManagerInConfigurationFile(e.XmlDocument, diImplementationType);
                }
            }, out _)
                   .WithoutPresetDiContainer()
                   .AddAdditionalDiModules(new TestModule2())
                   .RegisterModules()
                   .Start());
        }
        private void LoadConfiguration(Action <IContainerInfo, IConfiguration> testConfiguration,
                                       ConfigurationFileXmlDocumentLoadedEventHandler configurationFileXmlDocumentLoaded)
        {
            var diContainerBuilder = new DiContainerBuilder.DiContainerBuilder();

            var fileBasedConfigurationParameters = new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(
                                                                                            Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                                                                                        Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AttributeValueTransformers         = new [] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = configurationFileXmlDocumentLoaded
            };

            using (var containerInfo = diContainerBuilder.StartFileBasedDi(
                       fileBasedConfigurationParameters, out var loadedConfiguration)
                                       .WithoutPresetDiContainer()
                                       //.AddAdditionalDiModules(new SuccessfulConfigurationLoadTests.SuccessfulConfigurationLoadTests.TestModule2())
                                       .RegisterModules()
                                       .Start())
            {
                testConfiguration(containerInfo, loadedConfiguration);
            }
        }
        public static void ClassInitialize()
        {
            TestsHelper.SetupLogger();
            Log4Tests.LogLevel = LogLevel.Info;

            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                       .StartFileBasedDi(
                       new FileBasedConfigurationParameters(new FileBasedConfigurationFileContentsProvider(_configurationRelativePath),
                                                            Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AttributeValueTransformers = new[] { new FileFolderPathAttributeValueTransformer() },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));
                }
            }, out _)
                                       .WithoutPresetDiContainer().RegisterModules().Start())
            {
                var configuration = containerInfo.DiContainer.Resolve <IConfiguration>();
                _typeDefinitionsElement       = configuration.TypeDefinitions;
                _pluginTypeDefinitionsElement = configuration.PluginsSetup.GetPluginSetup(Plugin1Name).TypeDefinitions;
            }
        }
Beispiel #16
0
        public void CodeBasedConfigurationExample1()
        {
            TestsSharedLibrary.TestsHelper.SetupLogger();

            // Probing paths are used to re-solve the dependencies.
            var assemblyProbingPaths = new string[]
            {
                DiManagerHelpers.ThirdPartyLibsFolder,
                DiManagerHelpers.DynamicallyLoadedDllsFolder,
                DiManagerHelpers.GetDiImplementationInfo(DiImplementationType.Autofac).DiManagerFolder
            };

            var diImplementationInfo = DiManagerHelpers.GetDiImplementationInfo(DiImplementationType.Autofac);

            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                       .StartCodeBasedDi("IoC.Configuration.Autofac.AutofacDiManager",
                                                         diImplementationInfo.DiManagerAssemblyPath,
                                                         new ParameterInfo[0],
                                                         Helpers.TestsEntryAssemblyFolder,
                                                         assemblyProbingPaths)
                                       .WithoutPresetDiContainer()
                                       // Note, AddNativeModule() to add native modules (e.g., instances of  Autofac.AutofacModule or
                                       // Ninject.Modules.NinjectModule) // and AddDiModules to add IoC.Configuration modules (i.e.,
                                       // instances IoC.Configuration.DiContainer.IDiModule), can be called multiple times, without
                                       // any restriction on the order in which these methods are called.
                                       .AddNativeModule("Modules.Autofac.AutofacModule1",
                                                        Path.Combine(DiManagerHelpers.DynamicallyLoadedDllsFolder, "TestProjects.Modules.dll"),
                                                        new[] { new ParameterInfo(typeof(int), 18) })
                                       .AddDiModules(new TestDiModule())
                                       .RegisterModules()
                                       .Start())
            {
                var container = containerInfo.DiContainer;

                Assert.IsNotNull(containerInfo.DiContainer.Resolve <IInterface6>());
            }
        }
Beispiel #17
0
    private void LoadDiContainerAndValidate(CreateFileBasedConfigurationParametersDelegate createFileBasedConfigurationParameters,
                                            [CanBeNull, ItemNotNull] IEnumerable <string> additionalReferencedAssemblies = null,
                                            [CanBeNull] ILoadedAssemblies loadedAssemblies = null, [CanBeNull] Action <XmlDocument> modifyConfigurationFileOnLoad = null)
    {
        loadedAssemblies ??= new LoadedAssemblies(false);

        var fileBasedConfigurationParameters = createFileBasedConfigurationParameters(
            new FileBasedConfigurationFileContentsProvider(Path.Combine(Helpers.TestsEntryAssemblyFolder, _configurationRelativePath)),
            Helpers.TestsEntryAssemblyFolder, loadedAssemblies);

        if (additionalReferencedAssemblies != null)
        {
            fileBasedConfigurationParameters.AdditionalReferencedAssemblies = additionalReferencedAssemblies;
        }

        fileBasedConfigurationParameters.AttributeValueTransformers         = new[] { new FileFolderPathAttributeValueTransformer() };
        fileBasedConfigurationParameters.ConfigurationFileXmlDocumentLoaded = (sender, e) =>
        {
            Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));

            // Lets explicitly set the DiManager to Autofac. Since we are going to test failure, the Di manager implementation does not matter.
            // However, this will give us predictability on what modules will be enabled.
            e.XmlDocument.SelectElement("/iocConfiguration/diManagers").SetAttributeValue(ConfigurationFileAttributeNames.ActiveDiManagerName, _diImplementationType.ToString());
            modifyConfigurationFileOnLoad?.Invoke(e.XmlDocument);
        };

        var ioCConfigurator = new DiContainerBuilder.DiContainerBuilder()
                              .StartFileBasedDi(fileBasedConfigurationParameters, out _)
                              .WithoutPresetDiContainer()
                              .RegisterModules().Start();

        var diContainer = ioCConfigurator.DiContainer;

        Assert.AreEqual(18, diContainer.Resolve <IDogWeightsCalculator>().GetDogWeightInKilograms());
        diContainer.Dispose();
    }
        public void LoadFromXmlConfigurationFile()
        {
            using (var containerInfo = new DiContainerBuilder.DiContainerBuilder()
                                       .StartFileBasedDi(
                       new FileBasedConfigurationParameters(
                           new FileBasedConfigurationFileContentsProvider(
                               Path.Combine(Helpers.TestsEntryAssemblyFolder, "IoCConfiguration_Overview.xml")),
                           // Provide the entry assembly folder. Normally this is the folder,
                           // where the executable file is. However for test projects this might not
                           // be the case. This folder will be used in assembly resolution.
                           Helpers.TestsEntryAssemblyFolder, new LoadedAssembliesForTests())
            {
                AdditionalReferencedAssemblies = new string[]
                {
                    // List additional assemblies that should be added to dynamically generated assembly as references
                    Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly1.dll"),
                    Path.Combine(Helpers.GetTestFilesFolderPath(), @"DynamicallyLoadedDlls\TestProjects.DynamicallyLoadedAssembly2.dll")
                },
                // Set the value of AttributeValueTransformers to list of
                // IoC.Configuration.AttributeValuesProvider.IAttributeValueTransformer instances
                // to change some xml attribute values when the xml configuration is loaded,
                // before the configuration is parsed.
                // Good example of implementation of IoC.Configuration.AttributeValuesProvider.IAttributeValueTransformer
                // is IoC.Configuration.Tests.FileFolderPathAttributeValueTransformer.
                AttributeValueTransformers = new IAttributeValueTransformer []
                {
                    new FileFolderPathAttributeValueTransformer()
                },
                ConfigurationFileXmlDocumentLoaded = (sender, e) =>
                {
                    // Replace some elements in e.XmlDocument if needed,
                    // before the configuration is loaded.
                    // For example, we can replace the value of attribute 'activeDiManagerName' in element
                    // iocConfiguration.diManagers to use a different DI manager (say
                    // switch from Autofac to Ninject).
                    Helpers.EnsureConfigurationDirectoryExistsOrThrow(e.XmlDocument.SelectElement("/iocConfiguration/appDataDir").GetAttribute("path"));
                    e.XmlDocument.SelectElements("/iocConfiguration/diManagers")
                    .First()
                    .SetAttributeValue("activeDiManagerName", "Autofac");
                }
            }, out _)

                                       // Note, most of the time we will need to call method WithoutPresetDiContainer().
                                       // However, in some cases, we might need to create an instance of IoC.Configuration.DiContainer.IDiContainer,
                                       // and call the method WithDiContainer(IoC.Configuration.DiContainer.IDiContainer diContainer) instead.
                                       // This might be necessary when using the IoC.Configuration to configure dependency injection in
                                       // ASP.NET Core projects.
                                       // An example implementation of IDIContainer is IoC.Configuration.Autofac.AutofacDiContainer in
                                       // Nuget package IoC.Configuration.Autofac.
                                       .WithoutPresetDiContainer()

                                       // Note, native and IoC.Configuration modules can be specified in XML configuration file, in
                                       // iocConfiguration/dependencyInjection/modules/module elements.
                                       // However, if necessary, AddAdditionalDiModules() and AddNativeModules() can be used to load additional
                                       // IoC.Configuration modules (instances of IoC.Configuration.DiContainer.IDiModule), as well
                                       // as native (e.g, Ninject or Autofac) modules.
                                       // Also, AddAdditionalDiModules() and AddNativeModules() can be called multiple times in any order.
                                       .AddAdditionalDiModules(new TestDiModule())
                                       .AddNativeModules(CreateModule <object>("Modules.Autofac.AutofacModule1",
                                                                               new ParameterInfo[] { new ParameterInfo(typeof(int), 5) }))
                                       .RegisterModules()
                                       .Start())
            {
                var diContainer = containerInfo.DiContainer;

                // Once the configuration is loaded, resolve types using IoC.Configuration.DiContainer.IDiContainer
                // Note, interface IoC.Configuration.DiContainerBuilder.IContainerInfo extends System.IDisposable,
                // and should be disposed, to make sure all the resources are properly disposed of.
                var resolvedInstance = containerInfo.DiContainer.Resolve <SharedServices.Interfaces.IInterface7>();
            }
        }