public static void CompleteInitialization()
        {
            Assembly[] partsAssemblies;

            lock (_initLock)
            {
                if (_isInitialized)
                    return;

                _isInitialized = true;

                partsAssemblies = _partAssemblies.Union(FindWebApplicationAssemblies()).ToArray();
            }

            var conventions = new ConventionBuilder()
                .WithMvcConventions()
                .WithEagerConstructionSupport();

            conventions.ForTypesUnderNamespace("Parts").Export().ExportInterfaces();

            var container = new ContainerConfiguration()
                .WithDefaultConventions(conventions)
                .WithAssemblies(partsAssemblies)
                .WithApplicationSettings()
                .CreateContainer();

            MvcCompositionProvider.Initialize(container);
            CompositionFilterProvider.Install(FilterProviders.Providers);
            ImportCapableFilterAttributeFilterProvider.Install(FilterProviders.Providers);

            container.ConstructEagerParts();
        }
        public static void RegistrationByConvention(this Container container, 
            BehaviorConfiguration configuration, 
            Action<IConventionBuilderSyntax<Lifestyle, Container>> convention)
        {
            if (configuration == null)
            {
                configuration = BehaviorConfiguration.Default;
            }

            var logger = new DiagnosticLogger(configuration);
            var serviceMappingTracker = new ServiceMappingTracker(logger);
            var implementationFilter = new ImplementationFilter();
            var adapter = new SimpleInjectorContainerAdapter(container, serviceMappingTracker, implementationFilter);
            var configServiceFilter = ((IBehaviorConfiguration)configuration).GetServiceFilter();

            var asmSelector = new AssemblySelector();
            var serviceExtractor = new ServiceExtractor();
            var containerDecorator = new ContainerLogger<Lifestyle>(adapter, logger);
            var serviceFilterAggregator = new ServiceFilterAggregator(new IServiceFilter[] { configServiceFilter, implementationFilter, serviceExtractor, serviceMappingTracker });
            using (var builder = new ConventionBuilder<Lifestyle>(containerDecorator,
                asmSelector,
                serviceFilterAggregator,
                serviceExtractor))
            {
                var importer = new ConventionBuilderSyntaxDecorator<Lifestyle, Container>(builder, container, implementationFilter, asmSelector);
                convention(importer);
            }
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        public void UsingNLog()
        {
            var writer = GetTrace();

            LoggingConfiguration config = new LoggingConfiguration();

            TraceTarget target = new TraceTarget();
            target.Layout = "NLOG [${level:uppercase=true}] ${message}";
            config.AddTarget("trace", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));

            LogManager.Configuration = config;

            ConventionBuilder.Logger = t => LogManager.GetLogger(t);

            var builder = new ConventionBuilder();
            builder.ScanThisAssembly().For<HandlerConventions>();

            var convention = builder.Build();

            Approvals.VerifyAll(writer
                .ToString()
                .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                .OrderBy(s => s), "");
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        static partial void AddWinRTSpecificConventions( ConventionBuilder builder )
        {
            var assembly = new PublicKeyTokenSpecification( typeof( Host ) );
            var settingsFlyout = new SettingsFlyoutSpecification();

            builder.ForTypesMatching( settingsFlyout.IsSatisfiedBy ).Export().Export<SettingsFlyout>().ExportInterfaces( assembly.IsSatisfiedBy ).ImportProperties( p => p != null && p.Name == "Model" );
        }
        public void StandardExportInterfacesShouldWork()
        {
            // Export all interfaces except IDisposable, Export contracts on types without interfaces. except for disposable types
            var builder = new ConventionBuilder();
            builder.ForTypesMatching((t) => true).ExportInterfaces();
            builder.ForTypesMatching((t) => t.GetTypeInfo().ImplementedInterfaces.Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();

            var container = new ContainerConfiguration()
                .WithPart<Standard>(builder)
                .WithPart<Dippy>(builder)
                .WithPart<Derived>(builder)
                .WithPart<BareClass>(builder)
                .CreateContainer();

            var importer = new Importer();
            container.SatisfyImports(importer);

            Assert.NotNull(importer.First);
            Assert.True(importer.First.Count() == 3);
            Assert.NotNull(importer.Second);
            Assert.True(importer.Second.Count() == 3);
            Assert.NotNull(importer.Third);
            Assert.True(importer.Third.Count() == 3);
            Assert.NotNull(importer.Fourth);
            Assert.True(importer.Fourth.Count() == 3);
            Assert.NotNull(importer.Fifth);
            Assert.True(importer.Fifth.Count() == 3);

            Assert.Null(importer.Base);
            Assert.Null(importer.Derived);
            Assert.Null(importer.Dippy);
            Assert.Null(importer.Standard);
            Assert.Null(importer.Disposable);
            Assert.NotNull(importer.BareClass);
        }
Exemplo n.º 8
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();
        }
Exemplo n.º 9
0
        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());
        }
Exemplo n.º 10
0
 protected static CompositionContext CreateContainer(ConventionBuilder rb, params Type[] types)
 {
     return new ContainerConfiguration()
         .WithParts(types)
         .WithDefaultConventions(rb)
         .CreateContainer();
 }
Exemplo n.º 11
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);
 }
Exemplo n.º 12
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();
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        public void AsContractName_AndContractType_SetsContractNameAndType()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export((e) => e.AsContractName("hey").AsContractType(typeof(IFoo)));

            ExportAttribute exportAtt = GetExportAttribute(builder);
            Assert.Equal("hey", exportAtt.ContractName);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
        }
        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);
        }
Exemplo n.º 17
0
        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);
        }
Exemplo n.º 18
0
        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));
        }
Exemplo n.º 19
0
        public void AsContractTypeOfT_SetsContractType()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export((e) => e.AsContractType<IFoo>());

            ExportAttribute exportAtt = GetExportAttribute(builder);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
            Assert.Null(exportAtt.ContractName);
        }
Exemplo n.º 20
0
        static partial void AddPlatformSpecificConventions( ConventionBuilder builder )
        {
            var assembly = new PublicKeyTokenSpecification( typeof( Host ) );
            var window = new AssignableSpecification<Window>().And( new AssignableSpecification<IShellView>().Not() );
            var userControl = new AssignableSpecification<UserControl>().And( new AssignableSpecification<IShellView>().Not() );

            builder.ForTypesMatching( window.IsSatisfiedBy ).Export().ExportInterfaces( assembly.IsSatisfiedBy ).ImportProperties( p => p != null && p.Name == "Model" );
            builder.ForTypesMatching( userControl.IsSatisfiedBy ).Export().ExportInterfaces( assembly.IsSatisfiedBy ).ImportProperties( p => p != null && p.Name == "Model" );
        }
Exemplo n.º 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);
        }
Exemplo n.º 22
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 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);
        }
Exemplo n.º 24
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 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);
        }
Exemplo n.º 26
0
        static partial void AddPlatformSpecificConventions( ConventionBuilder builder )
        {
            var assembly = new PublicKeyTokenSpecification( typeof( Host ) );
            var page = new PageSpecification();
            var userControl = new UserControlSpecification();

            builder.ForTypesMatching( page.IsSatisfiedBy ).Export().Export<Page>().ExportInterfaces( assembly.IsSatisfiedBy ).ImportProperties( p => p != null && p.Name == "Model" );
            builder.ForTypesMatching( userControl.IsSatisfiedBy ).Export().ExportInterfaces( assembly.IsSatisfiedBy ).ImportProperties( p => p != null && p.Name == "Model" );
            AddWinRTSpecificConventions( builder );
        }
Exemplo n.º 27
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);
        }
Exemplo n.º 28
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);
        }
        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);
        }
Exemplo n.º 30
0
        public static void BuildMefConventions(ConventionBuilder conventionBuilder)
        {
            Contract.Requires(conventionBuilder != null);

            // Export views as FrameworkElement with contract name as the type full name, so the ViewLocator can find it.
            conventionBuilder.ForTypesMatching(t => t.Name.EndsWith("View"))
                             .Export<FrameworkElement>(
                                 builder =>
                                 builder.AsContractName(t => t.FullName));
        }