public void Circular_dependencies_in_large_object_graphs_should_be_detected_even_for_dynamic_registrations() { // register dynamically var assembly = typeof(Issue546_Recursive_dependency_isnt_detected_in_large_object_graphs).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); // use shared service exports to compose multiple providers var serviceExports = new Dictionary <string, IList <KeyValuePair <object, ExportedRegistrationInfo> > >(); // create a separate DynamicRegistrationProvider for each lazy registration // to simulate that each ICommand is located in a different assembly var dynamicRegistrations = lazyRegistrations .Select(r => new[] { r } .GetLazyTypeRegistrationProvider( otherServiceExports: serviceExports, typeProvider: t => assembly.GetType(t))) .ToArray(); // Test that dynamic resolution also detects the circular dependency //================================================================== // simulate large object graph by lowering the max size var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations) .WithDependencyCountInLambdaToSplitBigObjectGraph(1)); // make sure that CircularDependencyRoot itself is available without loading the lazy assembly container.RegisterExports(typeof(CircularDependencyRoot)); Assert.Throws <ContainerException>(() => container.Resolve <CircularDependencyRoot>()); }
public void Lazy_import_of_commands_using_LazyFactory() { var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); var assemblyLoaded = false; var dynamicRegistrations = lazyRegistrations.GetLazyTypeRegistrationProvider(() => { assemblyLoaded = true; return(assembly); }); // Test that resolve works //======================== var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); // make sure that CommandImporter itself is available without loading the lazy assembly container.RegisterExports(typeof(CommandImporter)); // the same resolution code as in previous test //======================== var cmds = container.Resolve <CommandImporter>(); Assert.IsFalse(assemblyLoaded); Assert.IsNotNull(cmds.LazyHandler); Assert.IsNotNull(cmds.LazyHandler.Value); Assert.IsTrue(assemblyLoaded); Assert.IsNotNull(cmds.Commands); Assert.AreEqual(2, cmds.Commands.Count()); Assert.AreEqual("Sample command, Another command", string.Join(", ", cmds.Commands.Select(c => c.Metadata.Name).OrderByDescending(c => c))); }
public DryIocResolution(Container container, PluginsConfiguration configuration) { this.Container = container.OpenScope(); var assemblies = new List <Assembly>(); try { foreach (var directory in configuration.Directories) { foreach (var f in Directory.GetFiles(directory, "*Plugin*.dll", SearchOption.AllDirectories)) { assemblies.Add(Assembly.LoadFrom(f)); } } } catch (System.Reflection.ReflectionTypeLoadException ex) { var firstFive = string.Join(Environment.NewLine, ex.LoaderExceptions.Take(5).Select(it => it.Message)); System.Diagnostics.Debug.WriteLine(ex.ToString()); System.Diagnostics.Debug.WriteLine(firstFive); throw new FrameworkException("Error loading plugins. Can't load plugins. {0}".With(firstFive), ex); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); throw new FrameworkException("Error loading plugins.", ex); } AttributedModel.DefaultSetup(this.Container); this.Container.RegisterExports(assemblies.ToArray()); }
public void Should_properly_print_registration_info_with_default_reuse_type() { var info = AttributedModel.GetExportedRegistrations(typeof(PrintToCodeNoCreationPolicyExample)).Single(); var code = info.ToCode(); var codeValue = code.ToString(); Assert.That(codeValue, Is.EqualTo(@" new ExportedRegistrationInfo { ImplementationType = typeof(DryIoc.MefAttributedModel.UnitTests.CUT.PrintToCodeNoCreationPolicyExample), Exports = new[] { new ExportInfo(typeof(DryIoc.MefAttributedModel.UnitTests.CUT.PrintToCodeNoCreationPolicyExample), 2, DryIoc.IfAlreadyRegistered.AppendNotKeyed), new ExportInfo(typeof(DryIoc.MefAttributedModel.UnitTests.CUT.IPrintToCode), 2, DryIoc.IfAlreadyRegistered.AppendNotKeyed), }, OpenResolutionScope = false, AsResolutionCall = false, AsResolutionRoot = false, PreventDisposal = false, WeaklyReferenced = false, AllowDisposableTransient = false, TrackDisposableTransient = false, UseParentReuse = false, HasMetadataAttribute = false, FactoryType = DryIoc.FactoryType.Service, ConditionType = null }")); }
public void Given_deserialized_data_When_registering_scanned_data_into_container_Then_metadata_should_correctly_registered_too() { var assembly = typeof(TransientService).GetAssembly(); var services = AttributedModel.Scan(new[] { assembly }).ToArray(); if (File.Exists(DATA_FILE)) { File.Delete(DATA_FILE); } var serializer = new Serializer(); using (var file = File.Create(DATA_FILE)) serializer.Serialize(services, file); ExportedRegistrationInfo[] infos; using (var file = File.OpenRead(DATA_FILE)) infos = serializer.Deserialize <ExportedRegistrationInfo[]>(file); var container = new Container().WithMef(); container.RegisterExports(infos); var factories = container.Resolve <Meta <Func <IServiceWithMetadata>, IViewMetadata>[]>(); Assert.That(factories.Length, Is.EqualTo(3)); }
public void Lazy_import_of_Actions() { var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); var assemblyLoaded = false; var dynamicRegistrations = lazyRegistrations.GetLazyTypeRegistrationProvider(() => { assemblyLoaded = true; return(assembly); }); // Test that resolve works fine with the non-lazy scenario //======================== var cnt = new Container().WithMef(); cnt.RegisterExports(typeof(ActionExporter), typeof(ActionImporter)); // validate imported metadata var importer = cnt.Resolve <ActionImporter>(); Assert.AreEqual(2, importer.Actions.Length); Assert.AreEqual("One, Two", string.Join(", ", importer.Actions.Select(a => a.Metadata["Name"].ToString()).OrderBy(n => n))); // validate imported actions var action1 = importer.Actions.First(m => m.Metadata["Name"].Equals("One")).Value; Assert.DoesNotThrow(() => action1()); var action2 = importer.Actions.First(m => m.Metadata["Name"].Equals("Two")).Value; Assert.Throws <NotImplementedException>(() => action2()); // Test that resolve works with the lazy scenario //======================== var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); // make sure that ActionImporter itself is available without loading the lazy assembly container.RegisterExports(typeof(ActionImporter)); importer = container.Resolve <ActionImporter>(); Assert.IsFalse(assemblyLoaded); // validate imported metadata Assert.IsNotNull(importer.Actions); Assert.AreEqual(2, importer.Actions.Length); // todo: fails here with "One, One" instead of "One, Two" Assert.AreEqual("One, Two", string.Join(", ", importer.Actions.Select(a => a.Metadata["Name"].ToString()).OrderBy(n => n))); Assert.IsFalse(assemblyLoaded); // validate imported actions action1 = importer.Actions.First(m => m.Metadata["Name"].Equals("One")).Value; Assert.IsTrue(assemblyLoaded); Assert.DoesNotThrow(() => action1()); action2 = importer.Actions.First(m => m.Metadata["Name"].Equals("Two")).Value; Assert.Throws <NotImplementedException>(() => action2()); }
public void ExportedRegistrationInfo_has_non_null_metadata_provided_by_ExportMetadataAttribute() { var regs = AttributedModel.Scan(new[] { typeof(WithExportMetadataOnlyKeyValue).GetAssembly() }); var reg = regs.Single(r => r.ImplementationType == typeof(WithExportMetadataOnlyKeyValue)); Assert.IsNotNull(reg.GetSetup().Metadata); Assert.IsTrue(reg.GetSetup().MatchesMetadata("b", 2)); }
public void Lazy_import_of_commands_using_custom_DynamicRegistrationProvider() { var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); var assemblyLoaded = false; Func <string, Type> typeProvider = typeName => { assemblyLoaded = true; return(assembly.GetType(typeName)); }; var commandRegistrations = lazyRegistrations .Where(r => r.ImplementationTypeFullName.EndsWith("Command")) .Select(r => new DynamicRegistration(r.CreateFactory(typeProvider))) .ToArray(); Rules.DynamicRegistrationProvider getDynamicRegistrations = (type, key) => { if (type == typeof(ICommand)) { return(commandRegistrations); } return(null); }; // Test that resolve works //======================== var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(getDynamicRegistrations)); // make sure that CommandImporter itself is available without loading the lazy assembly container.RegisterExports(typeof(CommandImporter)); container.RegisterExports(typeof(ObjectHandler)); // the same resolution code as in previous test //======================== var cmds = container.Resolve <CommandImporter>(); Assert.IsFalse(assemblyLoaded); Assert.IsNotNull(cmds.LazyHandler); Assert.IsNotNull(cmds.LazyHandler.Value); Assert.IsFalse(assemblyLoaded); Assert.IsNotNull(cmds.Commands); Assert.AreEqual(2, cmds.Commands.Count()); Assert.AreEqual("Sample command, Another command", string.Join(", ", cmds.Commands.Select(c => c.Metadata.Name).OrderByDescending(c => c))); Assert.IsFalse(assemblyLoaded); var command = cmds.Commands.First().Value; Assert.IsNotNull(command); Assert.IsTrue(assemblyLoaded); }
public void Can_get_registration_info_with_implementation_type_replaced_by_its_full_name() { var registrationInfo = AttributedModel.GetExportedRegistrations(typeof(Frog)).Single().MakeLazy(); Assert.IsNotNull(registrationInfo.ImplementationTypeFullName); Assert.IsNotNull(registrationInfo.Exports[0].ServiceTypeFullName); var asm = GetType().GetAssembly(); var type = asm.GetType(registrationInfo.ImplementationTypeFullName); Assert.IsNotNull(type); }
public void Lazy_import_of_commands() { var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); var dynamicRegistrations = lazyRegistrations.GetLazyTypeRegistrationProvider(() => assembly); var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); var cmds = container.Resolve <CommandImporter>(); Assert.IsNotNull(cmds.Commands); Assert.AreEqual(2, cmds.Commands.Count()); Assert.AreEqual("Sample command, Another command", string.Join(", ", cmds.Commands.Select(c => c.Metadata.Name).OrderByDescending(c => c))); }
public void Lazy_import_should_detect_circular_dependencies() { // ordinary registration var nonLazyContainer = new Container().WithMef(); nonLazyContainer.RegisterExports(new[] { typeof(LazyRegistrationInfoStepByStep).Assembly }); // check that importing as non-lazy actually detects the circular dependency Assert.Throws <ContainerException>(() => { var cmds = nonLazyContainer.Resolve <CircularDependencyRoot>(); Assert.IsNotNull(cmds.Service); }); // register dynamically var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); // use shared service exports to compose multiple providers var serviceExports = new Dictionary <string, IList <KeyValuePair <object, ExportedRegistrationInfo> > >(); // create a separate DynamicRegistrationProvider for each lazy registration // to simulate that each ICommand is located in a different assembly var dynamicRegistrations = lazyRegistrations .Select(r => new[] { r } .GetLazyTypeRegistrationProvider( otherServiceExports: serviceExports, typeProvider: t => { return(assembly.GetType(t)); })) .ToArray(); // Test that dynamic resolution also detects the circular dependency //================================================================== var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); // make sure that CircularDependencyRoot itself is available without loading the lazy assembly container.RegisterExports(typeof(CircularDependencyRoot)); Assert.Throws <ContainerException>(() => { container.Resolve <CircularDependencyRoot>(); }); }
public void Lazy_import_of_commands_using_multiple_dynamic_registrations_of_the_same_service() { var assembly = typeof(LazyRegistrationInfoStepByStep).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); var assemblyLoaded = false; // use shared service exports to compose multiple providers var serviceExports = new Dictionary <string, IList <KeyValuePair <object, ExportedRegistrationInfo> > >(); // create a separate DynamicRegistrationProvider for each lazy registration // to simulate that each ICommand is located in a different assembly var dynamicRegistrations = lazyRegistrations .Select(r => new[] { r } .GetLazyTypeRegistrationProvider( otherServiceExports: serviceExports, typeProvider: t => { assemblyLoaded = true; return(assembly.GetType(t)); })) .ToArray(); // Test that resolve works //======================== var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); // make sure that CommandImporter itself is available without loading the lazy assembly container.RegisterExports(typeof(CommandImporter)); // the same resolution code as in previous test //======================== var cmds = container.Resolve <CommandImporter>(); Assert.IsFalse(assemblyLoaded); Assert.IsNotNull(cmds.LazyHandler); Assert.IsNotNull(cmds.LazyHandler.Value); Assert.IsTrue(assemblyLoaded); Assert.IsNotNull(cmds.Commands); Assert.AreEqual(2, cmds.Commands.Count()); // fails: only one command is imported Assert.AreEqual("Sample command, Another command", string.Join(", ", cmds.Commands.Select(c => c.Metadata.Name).OrderByDescending(c => c))); }
public void Register_interface_with_implementation_as_unregistered_type_resolution_rule() { const string assemblyFile = "DryIoc.Samples.CUT.dll"; var assembly = Assembly.LoadFrom(assemblyFile); var registrations = AttributedModel.Scan(new[] { assembly }); // create serializable registrations var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); // load the registrations and provide a way dynamically register them in container var dynamicRegistrations = lazyRegistrations.GetLazyTypeRegistrationProvider(() => assembly); var container = new Container().WithMef() .With(rules => rules.WithDynamicRegistrations(dynamicRegistrations)); var thing = container.Resolve <IThing>(); Assert.IsNotNull(thing); }
public void Given_scnanned_assembly_When_serialize_data_Then_deserialize_will_return_the_same_data() { var assembly = typeof(TransientService).GetAssembly(); var services = AttributedModel.Scan(new[] { assembly }).ToArray(); if (File.Exists(DATA_FILE)) { File.Delete(DATA_FILE); } var serializer = new Serializer(); using (var file = File.Create(DATA_FILE)) serializer.Serialize(services, file); ExportedRegistrationInfo[] infos; using (var file = File.OpenRead(DATA_FILE)) infos = serializer.Deserialize <ExportedRegistrationInfo[]>(file); Assert.AreEqual(services, infos); }
private IContainer CreateContainerWithDynamicRegistrations() { // dynamic registration var assembly = typeof(Issue543_Dynamic_Registrations_dont_respect_shared_creation_policy).Assembly; var registrations = AttributedModel.Scan(new[] { assembly }); var lazyRegistrations = registrations.MakeLazyAndEnsureUniqueServiceKeys(); // use shared service exports to compose multiple providers var serviceExports = new Dictionary <string, IList <KeyValuePair <object, ExportedRegistrationInfo> > >(); // create a separate DynamicRegistrationProvider for each lazy registration // to simulate that each ICommand is located in a different assembly var dynamicRegistrations = lazyRegistrations .Select(r => new[] { r } .GetLazyTypeRegistrationProvider( otherServiceExports: serviceExports, typeProvider: t => assembly.GetType(t))) .ToArray(); return(new Container().WithMef() .With(r => r.WithDefaultReuse(Reuse.Transient).WithDynamicRegistrations(dynamicRegistrations))); }
private void RegisterCommands() { // index only registrations related to this issue var lazyRegistrations = AttributedModel.Scan(new[] { typeof(Command1).Assembly }) .MakeLazyAndEnsureUniqueServiceKeys() .Where(r => r.ImplementationTypeFullName.IndexOf("Issue486") >= 0) .ToArray(); // Command1 and Command2 Assert.AreEqual(2, lazyRegistrations.Length); var typeProvider = new Func <string, Type>(t => typeof(Command1).Assembly.GetType(t)); // index export registrations by exported service type foreach (var reg in lazyRegistrations) { foreach (var export in reg.Exports) { var regs = DynamicRegistrations.GetOrAdd(export.ServiceTypeFullName, _ => new List <DynamicRegistration>()); regs.Add(new DynamicRegistration(reg.CreateFactory(typeProvider), serviceKey: export.ServiceKey)); } } }
public static void RegisterExportsWithInterception(this IRegistrator registrator, IEnumerable <Assembly> assemblies) { registrator.RegisterExportsWithInterception(AttributedModel.Scan(assemblies)); }