Beispiel #1
0
        // *** Protected Methods ***

        protected ContainerConfiguration GetOkraContainerConfiguration()
        {
            // Create a basic container configuration with,
            //    - The Okra assembly (via the INavigationManager interface)
            //    - The Okra.MEF assembly (via the OkraBootstrapper class)

            ConventionBuilder okraConventionBuilder = new ConventionBuilder();

            okraConventionBuilder.ForType<NavigationManager>().Export<INavigationManager>()
                                                                .Shared()
                                                                .SelectConstructor(ctors => ctors.First(), (info, builder) =>
                                                                {
                                                                    if (info.ParameterType == typeof(INavigationTarget))
                                                                        builder.AllowDefault();
                                                                });

            okraConventionBuilder.ForType<SettingsPaneManager>().Export<ISettingsPaneManager>().Shared();
            okraConventionBuilder.ForType<ActivationManager>().Export<IActivationManager>().Shared();
            okraConventionBuilder.ForType<SearchManager>().Export<ISearchManager>().Shared();
            okraConventionBuilder.ForType<ShareSourceManager>().Export<IShareSourceManager>().Shared();
            okraConventionBuilder.ForType<ShareTargetManager>().Export<IShareTargetManager>().Shared();
            okraConventionBuilder.ForType<LifetimeManager>().Export<ILifetimeManager>().Shared();
            okraConventionBuilder.ForType<StorageManager>().Export<IStorageManager>().Shared();
            okraConventionBuilder.ForType<LaunchActivationHandler>().Export<ILaunchActivationHandler>().Shared();

            return new ContainerConfiguration()
                        .WithAssembly(typeof(INavigationManager).GetTypeInfo().Assembly, okraConventionBuilder)
                        .WithAssembly(typeof(OkraBootstrapper).GetTypeInfo().Assembly);
        }
Beispiel #2
0
        public static void ConfigureContainer()
        {
            var containerConventions = new ConventionBuilder();

            containerConventions.ForType <DbProductRepository>()
            .ExportInterfaces()
            .SelectConstructorWithMostParameters()
            .InstancePerHttpRequest();

            containerConventions.ForType <DbLogger>()
            .ExportInterfaces()
            .SelectConstructorWithMostParameters()
            .InstancePerHttpRequest();

            containerConventions.ForType <ProductDbContext>()
            .Export()
            .InstancePerHttpRequest();

            containerConventions.ForTypesDerivedFrom <Controller>()
            .Export <IController>()
            .Export()
            .SelectConstructorWithMostParameters();

            var containerConfig = new ContainerConfiguration();

            containerConfig.WithAssembly(Assembly.GetExecutingAssembly(), containerConventions);

            containerConfig.CreateContainer().UseWithMvc();
        }
Beispiel #3
0
        // *** Protected Methods ***

        protected virtual ContainerConfiguration GetContainerConfiguration()
        {
            // Create a basic container configuration with,
            //    - The application's main assembly (i.e. that defines the current Application subclass)
            //    - The Cocoon assembly (via the INavigationManager interface)
            //    - The Cocoon.MEF assembly (via the CocoonBootstrapper class)

            ConventionBuilder cocoonConventionBuilder = new ConventionBuilder();

            cocoonConventionBuilder.ForType<NavigationManager>().Export<INavigationManager>()
                                                                .Shared()
                                                                .SelectConstructor(ctors => ctors.First(), (info, builder) =>
                                                                    {
                                                                        if (info.ParameterType == typeof(INavigationTarget))
                                                                            builder.AllowDefault();
                                                                    });

            cocoonConventionBuilder.ForType<ActivationManager>().Export<IActivationManager>().Shared();
            cocoonConventionBuilder.ForType<LifetimeManager>().Export<ILifetimeManager>().Shared();
            cocoonConventionBuilder.ForType<StorageManager>().Export<IStorageManager>().Shared();

            return new ContainerConfiguration()
                        .WithAssembly(Application.Current.GetType().GetTypeInfo().Assembly)
                        .WithAssembly(typeof(INavigationManager).GetTypeInfo().Assembly, cocoonConventionBuilder)
                        .WithAssembly(typeof(CocoonBootstrapper).GetTypeInfo().Assembly);
        }
Beispiel #4
0
        public static void ConfigureContainer()
        {
            var containerConventions = new ConventionBuilder();

            containerConventions.ForType<DbProductRepository>()
                .ExportInterfaces()
                .SelectConstructorWithMostParameters()
                .InstancePerHttpRequest();

            containerConventions.ForType<DbLogger>()
                .ExportInterfaces()
                .SelectConstructorWithMostParameters()
                .InstancePerHttpRequest();

            containerConventions.ForType<ProductDbContext>()
                .Export()
                .InstancePerHttpRequest();

            containerConventions.ForTypesDerivedFrom<Controller>()
                .Export<IController>()
                .Export()
                .SelectConstructorWithMostParameters();

            var containerConfig = new ContainerConfiguration();
            containerConfig.WithAssembly(Assembly.GetExecutingAssembly(), containerConventions);

            containerConfig.CreateContainer().UseWithMvc();
        }
Beispiel #5
0
        /// <summary>
        /// Exports portal classes and interfaces
        /// </summary>
        private static void RegisterPortalConventions(ConventionBuilder convention)
        {
            convention.ForType <Portal.MediaStreamStore>().Export <Portal.IMediaStreamStore>().Shared();
            convention.ForType <Portal.EntityFramework.PortalStore>().Export <Portal.IPortalStore>();

            convention.ForType <Portal.PortalValidator>().Export <Portal.IPortalValidator>().Shared();

            convention.ForType <Portal.PortalManager>()
            .ImportProperty(p => p.MediaStreamStore)
            .Export()
            .Shared(SharingBoundaries.HttpRequest);

            convention.ForType <Portal.PortalCompiler>().Export().Shared(SharingBoundaries.HttpRequest);
        }
        internal static void ApplyWebApiConventions(ConventionBuilder conventions)
        {
            Contract.Requires(conventions != null);

            conventions.ForTypesDerivedFrom <IModelConfiguration>().Export <IModelConfiguration>();
            conventions.ForType <TraceWriter>().Export <ITraceWriter>().Shared();
        }
Beispiel #7
0
        public void AddMetadataWithFunc_ShouldGeneratePartMetadataAttribute()
        {
            var builder = new ConventionBuilder();

            builder.ForType(typeof(FooImpl)).Export <IFoo>().AddPartMetadata("name", t => t.Name);

            Attribute[] attributes = GetAttributesFromMember(builder, typeof(FooImpl), null);
            Assert.Equal(2, attributes.Count());

            var exportAttribute = attributes.First((t) => t.GetType() == typeof(ExportAttribute)) as ExportAttribute;

            Assert.Equal(typeof(IFoo), exportAttribute.ContractType);
            Assert.Null(exportAttribute.ContractName);

            var mdAttribute = attributes.First((t) => t.GetType() == typeof(PartMetadataAttribute)) as PartMetadataAttribute;

            Assert.Equal("name", mdAttribute.Name);
            Assert.Equal(typeof(FooImpl).Name, mdAttribute.Value);

            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1");
            Assert.Equal(0, attributes.Count());

            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2");
            Assert.Equal(0, attributes.Count());

            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3");
            Assert.Equal(0, attributes.Count());
        }
Beispiel #8
0
        public void ExportOfT_ShouldGenerateSingleExportAttributeWithContractType()
        {
            var builder = new ConventionBuilder();

            builder.ForType(typeof(FooImpl)).Export <IFoo>();

            Attribute[] attributes = GetAttributesFromMember(builder, typeof(FooImpl), null);

            Assert.Equal(1, attributes.Count());

            var exportAttribute = attributes[0] as ExportAttribute;

            Assert.NotNull(exportAttribute);
            Assert.Equal(typeof(IFoo), exportAttribute.ContractType);
            Assert.Null(exportAttribute.ContractName);


            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P1");
            Assert.Equal(0, attributes.Count());

            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P2");
            Assert.Equal(0, attributes.Count());

            attributes = GetAttributesFromMember(builder, typeof(FooImpl), "P3");
            Assert.Equal(0, attributes.Count());
        }
Beispiel #9
0
        private static ConventionBuilder GetConventions()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IFormattingFilter>()
            .Export <IFormattingFilter>();

            conventions.ForTypesDerivedFrom <ISyntaxFormattingRule>()
            .Export <ISyntaxFormattingRule>();
            conventions.ForTypesDerivedFrom <ILocalSemanticFormattingRule>()
            .Export <ILocalSemanticFormattingRule>();
            conventions.ForTypesDerivedFrom <IGlobalSemanticFormattingRule>()
            .Export <IGlobalSemanticFormattingRule>();
            // New per-analyzer options mechanism, deriving
            // from VS Workspaces functionality
            conventions.ForTypesDerivedFrom <IOptionsProvider>()
            .Export <IOptionsProvider>();

            // Legacy CodeFormatter rules options mechanism
            conventions.ForType <FormattingOptions>()
            .Export();

            conventions.ForTypesDerivedFrom <IFormattingEngine>()
            .Export <IFormattingEngine>();

            return(conventions);
        }
Beispiel #10
0
        public void NotifyImportsSatisfiedTwice_ShouldSucceed()
        {
            var builder = new ConventionBuilder();

            builder.ForType <OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied1());
            builder.ForType <OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied2());
            CompositionHost container = new ContainerConfiguration()
                                        .WithPart <OnImportsSatisfiedMultipleClass>(builder)
                                        .WithPart <ExportValues>(builder)
                                        .CreateContainer();
            OnImportsSatisfiedMultipleClass test = container.GetExport <OnImportsSatisfiedMultipleClass>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(6, test.OnImportsSatisfiedInvoked);
        }
Beispiel #11
0
        public void AsContractName_AndContractType_ComputeContractNameFromType()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().ImportProperty((p) => p.IFooProperty, c => c.AsContractName(t => "Contract:" + t.FullName));

            ImportAttribute importAtt = GetImportAttribute(builder);
            Assert.Equal("Contract:" + typeof(IFoo).FullName, importAtt.ContractName);
        }
Beispiel #12
0
        public void AsContractName_AndContractType_SetsContractNameAndType()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AsContractName("hey"));

            ImportAttribute importAtt = GetImportAttribute(builder);
            Assert.Equal("hey", importAtt.ContractName);
        }
 public void CanSpecifyExportsWithConventionBuilder()
 {
     var rb = new ConventionBuilder();
     rb.ForType<BarePart>().Export();
     var cc = CreateContainer(rb, typeof(BarePart));
     var x = cc.GetExport<BarePart>();
     Assert.NotNull(x);
 }
Beispiel #14
0
        static partial void AddUISpecificConventions( ConventionBuilder builder )
        {
            var viewModel = new ViewModelSpecification();

            builder.ForTypesDerivedFrom<IShellView>().Export().Export<IShellView>().Shared();
            builder.ForTypesMatching( viewModel.IsSatisfiedBy ).Export();
            builder.ForType<EventBroker>().Export<IEventBroker>().Shared();
        }
Beispiel #15
0
        private ConventionBuilder GetInternalCompositionConventions(IList <TypeRegistration> typeRegistrations)
        {
            var conventionBuilder = new ConventionBuilder();

            typeRegistrations.GroupBy(tr => tr.ImplementationType)
            .Select(g =>
            {
                var partType = g.Key;

                if (g.Select(tr => tr.Lifetime).Distinct().Count() != 1)
                {
                    throw new InvalidOperationException("Conflicting lifetimes for an exported part");
                }

                var interfaces = g.Select(tr => tr.RegistrationType).Where(rt => rt.IsInterface).Distinct();
                var asSelf     = g.Select(tr => tr.RegistrationType).Any(rt => rt == partType);
                var lifeTime   = g.Select(tr => tr.Lifetime).Distinct().Single();

                return(new { PartType = partType, Interfaces = interfaces, ExportSelf = asSelf, Lifetime = lifeTime });
            })
            .ToList()
            .ForEach(x =>
            {
                Action <PartConventionBuilder> builderActions = (pcb) =>
                {
                    if (x.ExportSelf)
                    {
                        pcb.Export();
                    }

                    if (x.Interfaces.Any())
                    {
                        pcb.ExportInterfaces(t => x.Interfaces.Contains(t));
                    }

                    if (x.Lifetime == Lifetime.Singleton)
                    {
                        pcb.Shared();
                    }
                    else if (x.Lifetime == Lifetime.PerRequest)
                    {
                        pcb.Shared(PerRequestBoundary);
                    }
                };

                builderActions(conventionBuilder.ForType(x.PartType));
            });

            conventionBuilder
            .ForTypesMatching(t => typeof(INancyModule).IsAssignableFrom(t) &&
                              t.Assembly != typeof(NancyEngine).Assembly &&
                              t != typeof(DiagnosticModule))
            .Export()
            .ExportInterfaces()
            .Shared(PerRequestBoundary);

            return(conventionBuilder);
        }
        public void ImportPropertyTargetingBaseClass_ShouldGenerateImportManyForPropertySelected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ImportProperty(p => p.P3); // P3 is IEnumerable<int>

            var importManyAttribute = GetAttributeFromMember(builder, typeof(DerClass), "P3") as ImportManyAttribute;
            Assert.NotNull(importManyAttribute);
            Assert.Null(importManyAttribute.ContractName);
        }
Beispiel #17
0
        public void ExportInterfaceWithTypeOf1()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().Export<IFoo>();

            var exports = builder.GetCustomAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo()).Where<Attribute>(e => e is ExportAttribute).Cast<ExportAttribute>();
            Assert.Equal(1, exports.Count());
            Assert.Equal(exports.First().ContractType, typeof(IFoo));
        }
        public void AddImportConstraint_AddsImportConstraintMetadataAttribute()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AddMetadataConstraint("name", "val"));

            ImportMetadataConstraintAttribute importMetadataConstraint = GetImportMetadataConstraintAttribute(builder);
            Assert.Equal("name", importMetadataConstraint.Name);
            Assert.Equal("val", importMetadataConstraint.Value);
        }
        public void ExportInterfaceWithTypeOf2()
        {
            var builder = new ConventionBuilder();
            builder.ForType(typeof(CFoo)).Export((c) => c.AsContractType(typeof(IFoo)));

            var exports = builder.GetDeclaredAttributes(typeof(CFoo), typeof(CFoo).GetTypeInfo()).Where<Attribute>(e => e is ExportAttribute).Cast<ExportAttribute>();
            Assert.Equal(1, exports.Count());
            Assert.Equal(exports.First().ContractType, typeof(IFoo));
        }
Beispiel #20
0
        public void ConventionsCanApplyImportsToInheritedProperties()
        {
            var conventions = new ConventionBuilder();

            conventions.ForType <Imported>().Export();
            conventions.ForType <DerivedFromBaseWithImport>()
            .ImportProperty(b => b.Imported)
            .Export();

            var container = new ContainerConfiguration()
                            .WithDefaultConventions(conventions)
                            .WithParts(typeof(Imported), typeof(DerivedFromBaseWithImport))
                            .CreateContainer();

            var dfb = container.GetExport <DerivedFromBaseWithImport>();

            Assert.IsAssignableFrom(typeof(Imported), dfb.Imported);
        }
Beispiel #21
0
        public void AllowDefault_SetsAllowDefaultProperty()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AllowDefault());

            ImportAttribute importAtt = GetImportAttribute(builder);
            Assert.True(importAtt.AllowDefault);
            Assert.Null(importAtt.ContractName);
        }
Beispiel #22
0
        public void AsMany_And_ContractName_ChangesGeneratedAttributeToImportMany()
        {
            var builder = new ConventionBuilder();
            builder.ForType<FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AsContractName("hey").AsMany());

            ImportManyAttribute importAtt = GetImportManyAttribute(builder);
            Assert.NotNull(importAtt);
            Assert.Equal("hey", importAtt.ContractName);
        }
        public void WhenExportingInterfaces_NoPredicate_OnlyContractInterfacesAreExported()
        {
            var builder = new ConventionBuilder();
            builder.ForType<ClassWithLifetimeConcerns>().ExportInterfaces();

            var attributes = GetExportAttributes(builder, typeof(ClassWithLifetimeConcerns));
            var exportedContracts = attributes.Select(e => e.ContractType).ToArray();
            AssertX.Equivalent(s_contractInterfaces, exportedContracts);
        }
Beispiel #24
0
        protected override void Configure()
        {
            var convention = new ConventionBuilder();

            var allAssemblies = GetAllAssemblies();

            MefExtensions.ImportFromAttributes(convention, allAssemblies);

            convention.ForType <WindowManager>().Export(d => d.AsContractType(typeof(IWindowManager))).Shared();
            convention.ForType <EventAggregator>().Export(d => d.AsContractType(typeof(IEventAggregator))).Shared();

            var configuration = new ContainerConfiguration();

            configuration.WithAssemblies(allAssemblies, convention);
            DI.Container = MefContainer = configuration.CreateContainer();

            _container = new SimpleContainer();
        }
        public static void ImportFromAttributes(this ConventionBuilder convention, IEnumerable <Assembly> assemblies)
        {
            var exportedTypes = assemblies.SelectMany(d => d.ExportedTypes).ToList();
            var serviceTypes  = exportedTypes.Where(d => d.IsDefined(typeof(InheritedMefExportAttribute))).Select(s => new { type = s, attributes = s.GetCustomAttributes <InheritedMefExportAttribute>() }).ToList();
            var creationPolicyByServiceType = serviceTypes.ToDictionary(key => key.type, val => new { creationPolicyAttr = val.type.GetCustomAttribute <PartCreationPolicyAttribute>(), exportAttr = val.attributes });

            PartConventionBuilder partBuilder;

            foreach (var implementationType in exportedTypes)
            {
                partBuilder = null;
                if (implementationType.IsAbstract || implementationType.IsInterface || !implementationType.IsClass)
                {
                    continue;
                }

                PartCreationPolicyAttribute sharePolicy = null;
                foreach (var serviceType in creationPolicyByServiceType)
                {
                    if (!serviceType.Key.IsAssignableFrom(implementationType))
                    {
                        continue;
                    }

                    partBuilder = partBuilder ?? convention.ForType(implementationType);
                    foreach (var attribute in serviceType.Value.exportAttr)
                    {
                        if (string.IsNullOrEmpty(attribute.ContactName))
                        {
                            partBuilder.Export(config => config.AsContractType(attribute.ContractType));
                        }
                        else
                        {
                            partBuilder.Export(config => config.AsContractType(attribute.ContractType).AsContractName(attribute.ContactName));
                        }
                    }

                    sharePolicy = serviceType.Value.creationPolicyAttr;
                }


                if (sharePolicy != null)
                {
                    if (!string.IsNullOrEmpty(sharePolicy.SharingBoundary) && sharePolicy.SharingBoundary != PartCreationPolicyAttribute.DefaultShared)
                    {
                        partBuilder.Shared(sharePolicy.SharingBoundary);
                        continue;
                    }
                    if (sharePolicy.SharingBoundary == PartCreationPolicyAttribute.DefaultShared)
                    {
                        partBuilder.Shared();
                        continue;
                    }
                }
            }
        }
Beispiel #26
0
        public void ExportInterfaceWithTypeOf1()
        {
            var builder = new ConventionBuilder();

            builder.ForType <FooImpl>().Export <IFoo>();

            Collections.Generic.IEnumerable <ExportAttribute> exports = builder.GetCustomAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo()).Where <Attribute>(e => e is ExportAttribute).Cast <ExportAttribute>();
            Assert.Equal(1, exports.Count());
            Assert.Equal(typeof(IFoo), exports.First().ContractType);
        }
Beispiel #27
0
        public void AsContractName_AndContractType_ComputeContractNameFromType()
        {
            var builder = new ConventionBuilder();

            builder.ForType <FooImpl>().ImportProperty((p) => p.IFooProperty, c => c.AsContractName(t => "Contract:" + t.FullName));

            ImportAttribute importAtt = GetImportAttribute(builder);

            Assert.Equal("Contract:" + typeof(IFoo).FullName, importAtt.ContractName);
        }
        public void ImportPropertyTargetingDerivedClass_ShouldGenerateImportForPropertySelected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ImportProperty(p => p.P4); // P4 is string

            var importAttribute = GetAttributeFromMember(builder, typeof(DerClass), "P4") as ImportAttribute;

            Assert.NotNull(importAttribute);
            Assert.Null(importAttribute.ContractName);
        }
        public void WhenExportingInterfaces_PredicateSpecified_OnlyContractInterfacesAreSeenByThePredicate()
        {
            var seenInterfaces = new List<Type>();

            var builder = new ConventionBuilder();
            builder.ForType<ClassWithLifetimeConcerns>().ExportInterfaces(i => { seenInterfaces.Add(i); return true; });

            var attributes = GetExportAttributes(builder, typeof(ClassWithLifetimeConcerns));
            AssertX.Equivalent(s_contractInterfaces, seenInterfaces);
        }
        public void ImportPropertyTargetingDerivedClass_ShouldGenerateImportAttributeForP4Selected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ImportProperties((p) => p.Name == "P4");                // P1 is string

            var pAttr = GetAttributeFromMember(builder, typeof(DerClass), "P4") as ImportAttribute;

            Assert.NotNull(pAttr);                   // Ensure P1 has ImportAttribute (default configured)
            Assert.Null(pAttr.ContractName);
        }
Beispiel #31
0
        public void CanSpecifyExportsWithConventionBuilder()
        {
            var rb = new ConventionBuilder();

            rb.ForType <BarePart>().Export();
            var cc = CreateContainer(rb, typeof(BarePart));
            var x  = cc.GetExport <BarePart>();

            Assert.NotNull(x);
        }
Beispiel #32
0
        public void ExportInterfaceWithTypeOf2()
        {
            var builder = new ConventionBuilder();

            builder.ForType(typeof(FooImpl)).Export((c) => c.AsContractType(typeof(IFoo)));

            Collections.Generic.IEnumerable <ExportAttribute> exports = builder.GetDeclaredAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo()).Where <Attribute>(e => e is ExportAttribute).Cast <ExportAttribute>();
            Assert.Equal(1, exports.Count());
            Assert.Equal(exports.First().ContractType, typeof(IFoo));
        }
Beispiel #33
0
        public void InjectsPropertyImports()
        {
            var rb = new ConventionBuilder();

            rb.ForType <HasPropertyA>().ImportProperty(a => a.A).Export();
            var cc = CreateContainer(rb, typeof(HasPropertyA), typeof(A));
            var x  = cc.GetExport <HasPropertyA>();

            Assert.IsAssignableFrom <A>(x.A);
        }
        public void ImportPropertyTargetingBaseClass_ShouldGenerateImportManyForP3Selected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ImportProperties((p) => p.Name == "P3");                // P2 is Enumerable

            var pAttr = GetAttributeFromMember(builder, typeof(DerClass), "P3") as ImportManyAttribute;

            Assert.NotNull(pAttr);                   // Ensure P3 has ImportManyAttribute (default configured)
            Assert.Null(pAttr.ContractName);
        }
        public void ExportPropertyTargetingBaseClass_ShouldGenerateExportForPropertySelected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ExportProperty(p => p.P2); // P2 is string

            var exportAttribute = GetAttributeFromMember(builder, typeof(DerClass), "P2") as ExportAttribute;

            Assert.NotNull(exportAttribute);
            Assert.Null(exportAttribute.ContractName);
            Assert.Null(exportAttribute.ContractType);
        }
Beispiel #36
0
        public void ImportPropertyTargetingBaseClass_ShouldGenerateImportManyForP3Selected()
        {
            var builder = new ConventionBuilder();

            builder.ForType <DerClass>().ImportProperties((p) => p.Name == "P3");                // P2 is Enumerable

            var pAttr = GetAttributeFromMember(builder, typeof(DerClass), "P3") as ImportManyAttribute;

            Assert.NotNull(pAttr);                   // Ensure P3 has ImportManyAttribute (default configured)
            Assert.Null(pAttr.ContractName);
        }
Beispiel #37
0
        public void ImportPropertyTargetingDerivedClass_ShouldGenerateImportAttributeForP4Selected()
        {
            var builder = new ConventionBuilder();

            builder.ForType <DerClass>().ImportProperties((p) => p.Name == "P4");                // P1 is string

            var pAttr = GetAttributeFromMember(builder, typeof(DerClass), "P4") as ImportAttribute;

            Assert.NotNull(pAttr);                   // Ensure P1 has ImportAttribute (default configured)
            Assert.Null(pAttr.ContractName);
        }
Beispiel #38
0
        public void AsContractName_SetsContractName()
        {
            var builder = new ConventionBuilder();

            builder.ForType <FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AsContractName("hey"));

            ImportAttribute importAtt = GetImportAttribute(builder);

            Assert.AreEqual("hey", importAtt.ContractName);
            Assert.IsFalse(importAtt.AllowDefault);
        }
        public void ExportPropertyTargetingDerivedClass_ShouldGenerateExportForPropertySelected()
        {
            var builder = new ConventionBuilder();
            builder.ForType<DerClass>().ExportProperties((p) => p.Name == "P4");                // P1 is string

            var pAttr = GetAttributeFromMember(builder, typeof(DerClass), "P4") as ExportAttribute;

            Assert.NotNull(pAttr);
            Assert.Null(pAttr.ContractName);
            Assert.Null(pAttr.ContractType);
        }
Beispiel #40
0
        public void ImportPropertyTargetingBaseClass_ShouldGenerateImportManyForPropertySelected()
        {
            var builder = new ConventionBuilder();

            builder.ForType <DerClass>().ImportProperty(p => p.P3); // P3 is IEnumerable<int>

            var importManyAttribute = GetAttributeFromMember(builder, typeof(DerClass), "P3") as ImportManyAttribute;

            Assert.NotNull(importManyAttribute);
            Assert.Null(importManyAttribute.ContractName);
        }
Beispiel #41
0
        public void ImportPropertyTargetingDerivedClass_ShouldGenerateImportForPropertySelected()
        {
            var builder = new ConventionBuilder();

            builder.ForType <DerClass>().ImportProperty(p => p.P4); // P4 is string

            var importAttribute = GetAttributeFromMember(builder, typeof(DerClass), "P4") as ImportAttribute;

            Assert.NotNull(importAttribute);
            Assert.Null(importAttribute.ContractName);
        }
Beispiel #42
0
        public void ExportInterfaceWithTypeOf1()
        {
            var builder = new ConventionBuilder();

            builder.ForType <CFoo>().Export <IFoo>();

            IEnumerable <ExportAttribute> exports = builder.GetDeclaredAttributes(typeof(CFoo), typeof(CFoo).GetTypeInfo()).Where <Attribute>(e => e is ExportAttribute).Cast <ExportAttribute>();

            Assert.Equal(1, exports.Count());
            Assert.Equal(exports.First().ContractType, typeof(IFoo));
        }
Beispiel #43
0
        public void CanSpecifyLifetimeWithConventionBuilder()
        {
            var rb = new ConventionBuilder();

            rb.ForType <BarePart>().Export().Shared();
            var cc = CreateContainer(rb, typeof(BarePart));
            var x  = cc.GetExport <BarePart>();
            var y  = cc.GetExport <BarePart>();

            Assert.Same(x, y);
        }
Beispiel #44
0
        public void AllowDefault_SetsAllowDefaultProperty()
        {
            var builder = new ConventionBuilder();

            builder.ForType <FooImpl>().ImportProperty((p) => p.IFooProperty, (c) => c.AllowDefault());

            ImportAttribute importAtt = GetImportAttribute(builder);

            Assert.True(importAtt.AllowDefault);
            Assert.Null(importAtt.ContractName);
        }
		public override ContainerConfiguration Get( ContainerConfiguration parameter )
		{
			var mappings = source();
			var builder = new ConventionBuilder();
			foreach ( var mapping in mappings )
			{
				builder.ForType( mapping.Subject ).Export( conventionBuilder => conventionBuilder.AsContractType( mapping.ExportAs ?? mapping.Subject ) );	
			}
			var subjects = mappings.Select( mapping => mapping.Subject );
			var result = parameter.WithParts( subjects, builder );
			return result;
		}
Beispiel #46
0
        public void WireDynano()
        {
            var conventions = new ConventionBuilder();

            foreach( var type in Dynamo.GetInstanceNames())
            {
                conventions.ForType(Type.ReflectionOnlyGetType(type, false, true)).Export();
                //conventions.ForType(typeof(Type)).ExportInterfaces(i => i.IsPublic);
            }
            var config = new ContainerConfiguration().WithDefaultConventions(conventions);

            //var container = new CompositionContainer();
        }
        public void Bootstrap()
        {
            var conventions = new ConventionBuilder();
            conventions.ForTypesDerivedFrom<ICalculator>().Export<ICalculator>().Shared();
            conventions.ForType<Program>().ImportProperty<ICalculator>(p => p.Calculator);

            var configuration = new ContainerConfiguration()
                .WithDefaultConventions(conventions)
                .WithAssemblies(GetAssemblies("c:/addins"));

            using (CompositionHost host = configuration.CreateContainer())
            {
                host.SatisfyImports(this, conventions);
            }
        }
        /// <summary>
        /// Registers the components found in the given set of types.
        /// </summary>
        public static ContainerConfiguration RegisterComponents(this ContainerConfiguration configuration, IEnumerable<Type> types)
        {
            var builder = new ConventionBuilder();
            var candidates = types.Where(t => !t.GetTypeInfo().IsAbstract).ToArray();

            foreach (var type in candidates)
            {
                var info = type.GetTypeInfo();
                var component = info.GetCustomAttribute<ComponentAttribute>(true);
                if (component == null)
                    continue;

                var name = info.GetCustomAttributes<NamedAttribute>(true).Select(x => x.Name).FirstOrDefault();
                var part = builder.ForType(type);

                if (name != null)
                {
                    part.ExportInterfaces(
                            i => i != typeof(IDisposable),
                            (i, b) => b.AsContractName(name))
                        .Export(b => b.AsContractName(name));
                }
                else
                {
                    part.ExportInterfaces(i => i != typeof(IDisposable))
                        .Export();
                }

                if (component.IsSingleton)
                    part.Shared();

                part.SelectConstructor(ctors => ctors.OrderByDescending(ctor => ctor.GetParameters().Length).FirstOrDefault(),
                    (p, b) =>
                    {
                        var namedParam = p.GetCustomAttributes<NamedAttribute>(true).Select(x => x.Name).FirstOrDefault();
                        if (namedParam != null)
                            b.AsContractName(namedParam);
                    });
            }

            configuration.WithParts(candidates, builder);

            return configuration;
        }
        private static ConventionBuilder GetConventions()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom<IFormattingFilter>()
                .Export<IFormattingFilter>();

            conventions.ForTypesDerivedFrom<ISyntaxFormattingRule>()
                .Export<ISyntaxFormattingRule>();
            conventions.ForTypesDerivedFrom<ILocalSemanticFormattingRule>()
                .Export<ILocalSemanticFormattingRule>();
            conventions.ForTypesDerivedFrom<IGlobalSemanticFormattingRule>()
                .Export<IGlobalSemanticFormattingRule>();

            conventions.ForType<Options>()
                .Export();

            conventions.ForTypesDerivedFrom<IFormattingEngine>()
                .Export<IFormattingEngine>();

            return conventions;
        }
Beispiel #50
0
        public void NotifyImportsSatisfiedTwice_ShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForType<OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied1());
            builder.ForType<OnImportsSatisfiedMultipleClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied2());
            var container = new ContainerConfiguration()
                .WithPart<OnImportsSatisfiedMultipleClass>(builder)
                .WithPart<ExportValues>(builder)
                .CreateContainer();
            var test = container.GetExport<OnImportsSatisfiedMultipleClass>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(6, test.OnImportsSatisfiedInvoked);
        }
 public void CanSpecifyLifetimeWithConventionBuilder()
 {
     var rb = new ConventionBuilder();
     rb.ForType<BarePart>().Export().Shared();
     var cc = CreateContainer(rb, typeof(BarePart));
     var x = cc.GetExport<BarePart>();
     var y = cc.GetExport<BarePart>();
     Assert.Same(x, y);
 }
        public void MapType_OverridingSelectionOfConventionSelectedConstructor()
        {
            var builder = new ConventionBuilder();

            builder.
                ForTypesDerivedFrom<IFoo>().
                Export<IFoo>();

            builder.ForType<FooImplWithConstructors>()
                .SelectConstructor(cis => cis.ElementAtOrDefault(1));

            var fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();

            var constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
            var constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
            var constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();


            // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
            Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
            Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());

            var ci = constructor2;
            var attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
            Assert.Equal(1, attrs.Count());
            Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
        }
 public void InjectsPropertyImports()
 {
     var rb = new ConventionBuilder();
     rb.ForType<HasPropertyA>().ImportProperty(a => a.A).Export();
     var cc = CreateContainer(rb, typeof(HasPropertyA), typeof(A));
     var x = cc.GetExport<HasPropertyA>();
     Assert.IsAssignableFrom(typeof(A), x.A);
 }
Beispiel #54
0
        public void NotifyImportsSatisfiedAttributeAppliedToDerivedClassExportBase_ShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForType<OnImportsSatisfiedDerivedClass>().NotifyImportsSatisfied(p => p.OnImportsSatisfied());
            var container = new ContainerConfiguration()
                .WithPart<OnImportsSatisfiedTestClass>(builder)
                .WithPart<OnImportsSatisfiedDerivedClass>(builder)
                .WithPart<ExportValues>(builder)
                .CreateContainer();
            var test = container.GetExport<OnImportsSatisfiedTestClass>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(0, test.OnImportsSatisfiedInvoked);
        }