Example #1
0
        public void ExportInterfaceSelectorNull_ShouldThrowArgumentNull()
        {
            var builder = new ConventionBuilder();

            AssertExtensions.Throws <ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null));
            AssertExtensions.Throws <ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null, null));
        }
        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);
        }
Example #3
0
        public void ExportSelectorNull_ShouldThrowArgumentNull()
        {
            var builder = new ConventionBuilder();

            AssertExtensions.Throws <ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null));
            AssertExtensions.Throws <ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null, null));
            AssertExtensions.Throws <ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties <IFirst>(null));
            AssertExtensions.Throws <ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties <IFirst>(null, null));
        }
Example #4
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" );
        }
Example #5
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 );
        }
Example #6
0
        public void ExportBuilderApiTestsNull_ShouldThrowArgumentNull()
        {
            var builder = new ConventionBuilder();

            AssertExtensions.Throws <ArgumentNullException>("contractName", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName(null as string)));
            AssertExtensions.Throws <ArgumentException>("contractName", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName("")));
            AssertExtensions.Throws <ArgumentNullException>("getContractNameFromPartType", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName(null as Func <Type, string>)));
            AssertExtensions.Throws <ArgumentNullException>("type", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractType(null as Type)));
            AssertExtensions.Throws <ArgumentNullException>("name", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata(null as string, null as object)));
            AssertExtensions.Throws <ArgumentNullException>("name", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata(null as string, null as Func <Type, object>)));
            AssertExtensions.Throws <ArgumentNullException>("getValueFromPartType", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata("name", null as Func <Type, object>)));
        }
Example #7
0
        public static void RegisterMefDependencyResolver()
        {
            /**----------------------------------------
             * -- 说明:程序根据规则自动的导出部件
             * -----------------------------------------
             * 1. 所有的继承IHttpController的类
             * 2. 命名空间中包含.Support的所有类
             * ----------------------------------------
             */
            var conventions = new ConventionBuilder();

            // Export 所有IHttpController到容器
            conventions.ForTypesDerivedFrom <IHttpController>()
            .Export();

            // Export namespace {*.Support.*}
            conventions.ForTypesMatching(t => t.Namespace != null &&
                                         (t.Namespace.EndsWith(".Support") || t.Namespace.Contains(".Support.") || t.Namespace.EndsWith("Impl") || t.Namespace.Contains(".Impl.")))
            .Export()
            .ExportInterfaces();

            CompositionHost container = new ContainerConfiguration()
                                        .WithAssemblies(BuildManager.GetReferencedAssemblies().Cast <Assembly>(), conventions)
                                        .CreateContainer();


            // 设置WebApi的DependencyResolver
            GlobalConfiguration.Configuration.DependencyResolver = new MefDependencyResolver(container);
        }
Example #8
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" );
        }
Example #9
0
        /// <summary>
        /// Creates the <see cref="ConventionBuilder" /> builder instance to be used in
        /// conjunction with the project's <see cref="ContainerConfiguration" /> instance.
        /// </summary>
        /// <returns>
        /// The <see cref="ConventionBuilder" /> builder instance to be used in
        /// conjunction with the project's <see cref="ContainerConfiguration" /> instance.
        /// </returns>
        /// <remarks>
        /// In a nutshell, the instance returned by this method represents the following
        /// export rules: "For each type defined within the current assembly that has the
        /// <see cref="OperationAttribute" /> applied to it, export all
        /// <see cref="IOperation{T}" /> interfaces that it implements; a class may
        /// implement the interface multiple times - for different generic arguments
        /// (operand types)."
        ///
        /// In addition, the metadata (i.e., name and symbol) expressed by individual
        /// classes' <see cref="OperationAttribute" /> instances is added accordingly.
        /// </remarks>
        private static ConventionBuilder CreateConventionBuilder()
        {
            var  conventionBuilder = new ConventionBuilder();
            Type currentType       = null;
            var  processedTypes    = new HashSet <Type>();

            conventionBuilder
            .ForTypesMatching(IsOperationType)
            .ExportInterfaces(IsOperationInterface, ExportInterface);
            return(conventionBuilder);

            bool IsOperationType(Type type)
            {
                currentType = type;
                return(GetOperationAttribute(type) != null);
            };

            void ExportInterface(
                Type interfaceType,
                ExportConventionBuilder exportConventionBuilder)
            {
                exportConventionBuilder.AsContractType(interfaceType);
                if (processedTypes.Add(currentType))
                {
                    OperationAttribute attribute = GetOperationAttribute(currentType);
                    exportConventionBuilder.AddMetadata(
                        nameof(attribute.Name), attribute.Name);
                    exportConventionBuilder.AddMetadata(
                        nameof(attribute.Symbol), attribute.Symbol);
                }
            };
        }
Example #10
0
        static public void FromAssemblies(IEnumerable <Assembly> assemblies, params IExtensible[] extensibles)
        {
            var conventionBuilder = new ConventionBuilder();

            foreach (Type extensionType in extensibles.SelectMany(e => e.GetType().GetInterfacesFromDefinition(typeof(IExtensible <>)).Select(t => t.GenericTypeArguments[0])).Distinct())
            {
                conventionBuilder.ForTypesMatching(x => TypeFilter(x, extensionType)).Export(x => x.AsContractType(extensionType));
            }

            var nextExtensibles = new List <IExtensible>();
            IEnumerable <Assembly> enumerable = assemblies as IList <Assembly> ?? assemblies.ToList();

            ContainerConfiguration containerConfiguration = new ContainerConfiguration().WithAssemblies(enumerable, conventionBuilder);

            using (CompositionHost container = containerConfiguration.CreateContainer())
                foreach (IExtensible extensible in extensibles)
                {
                    nextExtensibles.AddRange(extensible.Extend(container).OfType <IExtensible>());
                }

            if (nextExtensibles.Count > 0)
            {
                FromAssemblies(enumerable, nextExtensibles);
            }
        }
Example #11
0
            internal Importer(IEnumerable <Assembly> assemblies)
            {
                var target = typeof(TContract);

                if (!target.IsInterface)
                {
                    throw new NotSupportedException($"type <{target}> should be an interface");
                }


                var conventionBuilder = new ConventionBuilder();

                conventionBuilder.ForTypesMatching(x => !x.IsAbstract && !x.IsInterface && x.IsClass && x.GetInterface(target.FullName) == target).Export <TContract>();

                this._container = new ContainerConfiguration()
                                  .WithAssemblies(assemblies, conventionBuilder)
                                  .CreateContainer();

                var list = new List <IExport <TContract> >();

                var exported = this._container.GetExports <ExportFactory <TContract, IDictionary <string, object> > >();

                foreach (var e in exported)
                {
                    var expando = new ExpandoObject() as IDictionary <string, object>;
                    foreach (var exp in e.Metadata)
                    {
                        expando.Add(exp);
                    }
                    var lz = e.CreateExport();
                    list.Add(new Proxy(lz, expando));
                }
                this.exportes = new ReadOnlyCollection <IExport <TContract> >(list);
            }
 /// <summary>
 ///   Override to setup up MEF export conventions.
 /// </summary>
 /// <param name="conventions"> </param>
 protected virtual void PrepareConventions(ConventionBuilder conventions)
 {
     // Automatic export of ViewModels.
     conventions
     .ForTypesMatching(type => type.Name.EndsWith("ViewModel"))
     .Export();
 }
Example #13
0
        /// <summary>
        /// Each time this is invoked, the search paths and patterns
        /// (built-in assemblies and directory paths + patterns) are
        /// searched to resolve matching components.  The results are
        /// cached and available in FoundProvider.
        /// </summary>
        private IEnumerable <TProv> FindProviders()
        {
            try
            {
                ConventionBuilder conventions = new ConventionBuilder();
                conventions.ForTypesMatching <TProv>(MatchProviderType)
                .Export <TProv>()
                .Shared();

                IEnumerable <string>   existingPaths = _searchPaths.Where(Directory.Exists);
                ContainerConfiguration configuration = new ContainerConfiguration()
                                                       .WithAssemblies(_builtInAssemblies, conventions)
                                                       .WithAssemblies(_searchAssemblies, conventions)
                                                       .WithAssembliesInPath(existingPaths.ToArray(), conventions);

                if (_adapter != null)
                {
                    configuration.WithProvider(_adapter);
                }

                using (CompositionHost container = configuration.CreateContainer())
                {
                    _foundProviders = container.GetExports <TProv>().ToArray();
                }

                return(_foundProviders);
            }
            catch (ReflectionTypeLoadException e)
            {
                Console.Error.WriteLine(e);
                throw;
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            var registration = new ConventionBuilder();

            registration.ForTypesDerivedFrom <IInterface1>().ImportProperties(pi => pi.Name == nameof(IInterface1.Interfaces))
            .ImportProperties(pi => pi.Name == nameof(IInterface1.Interface2), (pi, icb) => icb.AddMetadataConstraint("Active", nameof(Object2B)))
            .Export <IInterface1>();
            // Das hier funktioniert leider nicht für Interfaces. Letztendlich wird die PropertyInfo des Interfaces gegen die PropertyInfo der implementierenden Klasse geprüft. Und wird nur ein Standardobjektvergleich durchgeführt.
            //registration.ForType<IInterface1>().ImportProperty(i => i.Interface2).Export<IInterface1>();
            //registration.ForTypesDerivedFrom<IInterface1>().ImportProperties(i => i.PropertyType == typeof(IInterface2)).Export<IInterface1>();
            registration.ForTypesDerivedFrom <IInterface2>().Export <IInterface2>();
            registration.ForTypesMatching(t => t.Name == nameof(Object2B)).Export(builder => builder.AddMetadata("Active", nameof(Object2B)));
//            registration.ForType<Object1>().ImportProperties(i => i.PropertyType == typeof(IInterface2)).Export<Object1>();

            var configuration = new ContainerConfiguration().WithAssembly(typeof(Program).Assembly, registration);
            var container     = configuration.CreateContainer();

            var resolvedType0 = container.GetExport <IInterface1>();

//            var resolvedType1 = container.GetExport<Object1>();
//            var resolvedType2 = container.GetExport<Object2>();
//            var resolvedType3 = container.GetExport<ExternObject>();

//            IInterface1 externObject = new Object1();
//
//            container.SatisfyImports(externObject, registration);

            Console.Read();
        }
Example #15
0
        private void RegisterMefDependencyResolver()
        {
            /**----------------------------------------
             * -- 说明:程序根据规则自动的导出部件
             * -----------------------------------------
             * 1. 所有的继承IHttpController的类
             * 2. 命名空间中包含.Support的所有类
             * ----------------------------------------
             */
            var conventions = new ConventionBuilder();

            var lstAssemlby = new List <Assembly>();


            lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Repository.dll"));
            lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Service.dll"));
            lstAssemlby.Add(Assembly.GetExecutingAssembly());

            // Export namespace {*.Support.*}
            conventions.ForTypesMatching(t => t.Namespace != null &&
                                         (t.Namespace.EndsWith(".Support") || t.Namespace.Contains(".Support.") || t.Namespace.EndsWith("Impl") || t.Namespace.Contains(".Impl.")))
            .Export()
            .ExportInterfaces();
            container = new ContainerConfiguration()
                        .WithAssemblies(lstAssemlby.Cast <Assembly>(), conventions)
                        .CreateContainer();


            // 设置WebApi的DependencyResolver
            // GlobalConfiguration.Configuration.DependencyResolver = new MefDependencyResolver(container);
        }
Example #16
0
        protected override ContainerConfiguration GetContainerConfiguration()
        {
            var conventionBuilder = new ConventionBuilder();

            conventionBuilder.ForTypesMatching(type => type.FullName.EndsWith("View"))
                .Export(builder => builder.AsContractType<object>()
                                       .AsContractName("OkraPage")
                                       .AddMetadata("PageName", type => type.Name.Substring(0, type.Name.Length - 4)));

            conventionBuilder.ForTypesMatching(type => type.FullName.EndsWith("ViewModel"))
                .Export(builder => builder.AsContractType<object>()
                                       .AsContractName("OkraViewModel")
                                       .AddMetadata("PageName", type => type.Name.Substring(0, type.Name.Length - 9)));

            var ui = typeof(AppBootstrapper).GetTypeInfo().Assembly;
            return GetOkraContainerConfiguration().WithAssemblies(new[] { ui }, conventionBuilder);
        }
Example #17
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();
        }
Example #18
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);
        }
Example #19
0
        /// <summary>
        /// Creates the <see cref="ConventionBuilder" /> builder instance to be used in
        /// conjunction with the project's <see cref="ContainerConfiguration" /> instance.
        /// </summary>
        /// <returns>
        /// The <see cref="ConventionBuilder" /> builder instance to be used in
        /// conjunction with the project's <see cref="ContainerConfiguration" /> instance.
        /// </returns>
        /// <remarks>
        /// In a nutshell, the instance returned by this method represents the following
        /// export rules: "For each type defined within the current assembly that has the
        /// <see cref="OperationAttribute" /> applied to it, export all
        /// <see cref="IOperation{T}" /> interfaces that it implements; a class may
        /// implement the interface multiple times - for different generic arguments
        /// (operand types)."
        ///
        /// This project (unlike the CustomAttributes project) represents an alternative
        /// implementation that doesn't rely on MEF-managed metadata; an implementation of
        /// the <see cref="IMetadataProvider" /> interface is used instead.
        /// </remarks>
        private static ConventionBuilder CreateConventionBuilder()
        {
            var conventionBuilder = new ConventionBuilder();

            conventionBuilder
            .ForTypesMatching(IsOperationType)
            .ExportInterfaces(IsOperationInterface);
            return(conventionBuilder);
        }
Example #20
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));
        }
Example #21
0
        private CompositionHost CreateHost()
        {
            _config = new ContainerConfiguration();
            var convention = new ConventionBuilder();

            convention.ForTypesMatching <IHostingStartup>(
                t => typeof(IHostingStartup).IsAssignableFrom(t) && t != typeof(BootstrappingHostingStartup))
            .Export <IHostingStartup>()
            .NotifyImportsSatisfied(t => true);
            _config.WithAssemblies(_assemblies.Result, convention);
            return(_config.CreateContainer());
        }
 public void ExportBuilderApiTestsNull_ShouldThrowArgumentNull()
 {
     var builder = new ConventionBuilder();
     ExceptionAssert.ThrowsArgumentNull("contractName", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName(null as string)));
     ExceptionAssert.ThrowsArgument("contractName", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName("")));
     ExceptionAssert.ThrowsArgumentNull("getContractNameFromPartType", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractName(null as Func<Type, string>)));
     ExceptionAssert.ThrowsArgumentNull("type", () => builder.ForTypesMatching((t) => true).Export(c => c.AsContractType(null as Type)));
     ExceptionAssert.ThrowsArgumentNull("name", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata(null as string, null as object)));
     ExceptionAssert.ThrowsArgumentNull("name", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata(null as string, null as Func<Type, object>)));
     ExceptionAssert.ThrowsArgumentNull("getValueFromPartType", () => builder.ForTypesMatching((t) => true).Export(c => c.AddMetadata("name", null as Func<Type, object>)));
 }
        private static AttributedModelProvider DefineConventions()
        {
            var rb = new ConventionBuilder();

            rb.ForTypesDerivedFrom<IController>().Export();

            rb.ForTypesDerivedFrom<IHttpController>().Export();

            rb.ForTypesMatching(IsAPart)
                .Export()
                .ExportInterfaces();

            return rb;
        }
        private static void RegisterMefDependencyResolver()
        {
            /**----------------------------------------
             * -- 说明:程序根据规则自动的导出部件
             * -----------------------------------------
             * 1. 所有的继承IHttpController的类
             * 2. 命名空间中包含.Support的所有类
             * ----------------------------------------
             */
            var conventions = new ConventionBuilder();

            // Export 所有IHttpController到容器
            conventions.ForTypesDerivedFrom <IHttpController>()
            .Export();

            // Export namespace {*.Support.*}
            conventions.ForTypesMatching(t => t.Namespace != null &&
                                         (t.Namespace.EndsWith(".Support") || t.Namespace.Contains(".Support.") || t.Namespace.EndsWith("Impl") || t.Namespace.Contains(".Impl.")))
            .Export()
            .ExportInterfaces();


            var lstAssemlby = new List <Assembly>();


            var dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

            foreach (var item in dir.GetFiles("Intime.OPC.*.dll"))
            {
                lstAssemlby.Add(Assembly.LoadFrom(item.FullName));
            }


            //lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Repository.dll"));
            //lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Service.dll"));
            lstAssemlby.Add(Assembly.GetExecutingAssembly());

            container = new ContainerConfiguration()
                        .WithDefaultConventions(conventions)

                        .WithAssemblies(lstAssemlby)
                        .CreateContainer();

            //var a = container.GetExport<IRmaService>();
            //Console.WriteLine(a);


            // 设置WebApi的DependencyResolver
            // GlobalConfiguration.Configuration.DependencyResolver = new MefDependencyResolver(container);
        }
Example #25
0
        private static AttributedModelProvider DefineConventions()
        {
            var rb = new ConventionBuilder();

            rb.ForTypesDerivedFrom <IController>().Export();

            rb.ForTypesDerivedFrom <IHttpController>().Export();

            rb.ForTypesMatching(IsAPart)
            .Export()
            .ExportInterfaces();

            return(rb);
        }
Example #26
0
        public void StandardExportInterfacesInterfaceFilterConfiguredContractShouldWork()
        {
            //Same test as above only using default export builder
            var builder = new ConventionBuilder();

            builder.ForTypesMatching((t) => true).ExportInterfaces((iface) => iface != typeof(System.IDisposable), (iface, bldr) => bldr.AsContractType((Type)iface));
            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);
        }
Example #27
0
        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);
        }
Example #28
0
        public void NotifyImportsSatisfiedPropertiesAndFields_ShouldSucceed()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied5" || mi.Name == "OnImportsSatisfied6");
            CompositionHost container = new ContainerConfiguration()
                                        .WithPart <OnImportsSatisfiedTestClassPropertiesAndFields>(builder)
                                        .WithPart <ExportValues>(builder)
                                        .CreateContainer();
            OnImportsSatisfiedTestClassPropertiesAndFields test = container.GetExport <OnImportsSatisfiedTestClassPropertiesAndFields>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(0, test.OnImportsSatisfiedInvoked);
        }
Example #29
0
        public void NotifyImportsSatisfiedMultipleNotifications_ShouldSucceed()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied1");
            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(2, test.OnImportsSatisfiedInvoked);
        }
		public void BasicConvention( ContainerConfiguration configuration, ConventionBuilder sut )
		{
			sut.ForTypesMatching( DragonSpark.Specifications.Common.Always.IsSatisfiedBy ).Export();
			var types = this.Adapt().WithNested();
			var container = configuration.WithParts( types, sut ).CreateContainer();
			var export = container.GetExport<SomeExport>();
			Assert.NotNull( export );
			Assert.NotSame( export, container.GetExport<SomeExport>() );

			var invalid = container.TryGet<Item>();
			Assert.Null( invalid );

			var shared = container.GetExport<SharedExport>();
			Assert.NotNull( shared );
			Assert.Same( shared, container.GetExport<SharedExport>() );
		}
Example #31
0
        public static IDependencyResolver CreateWithDefaultConventions(Assembly[] appAssemblies)
        {
            var conventions = new ConventionBuilder();

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

            conventions.ForTypesMatching(t => t.Namespace != null && t.Namespace.EndsWith(".Parts"))
            .Export()
            .ExportInterfaces();

            var container = new ContainerConfiguration()
                            .WithAssemblies(appAssemblies, conventions)
                            .CreateContainer();

            return(new MefDependencyResolver(container));
        }
Example #32
0
        public void InsideTheLambdaCallGetCustomAttributesShouldSucceed()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesMatching((t) => !t.GetTypeInfo().IsDefined(typeof(MyDoNotIncludeAttribute), false)).Export();
            CompositionHost container = new ContainerConfiguration()
                                        .WithPart <MyNotToBeIncludedClass>(builder)
                                        .WithPart <MyToBeIncludedClass>(builder)
                                        .CreateContainer();

            var importer = new ImporterOfMyNotTobeIncludedClass();

            container.SatisfyImports(importer);

            Assert.Null(importer.MyNotToBeIncludedClass);
            Assert.NotNull(importer.MyToBeIncludedClass);
        }
Example #33
0
        static void Main(string[] args)
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesMatching(t => t.Namespace == typeof(Application).Namespace)
            .Export();

            var configuration = new ContainerConfiguration()
                                .WithDefaultConventions(conventions)
                                .WithAssembly(typeof(Program).Assembly);

            using (var container = configuration.CreateContainer())
            {
                var application = container.GetExport <Application>();
                application.Run("SuperIDE");
            }

            Console.ReadKey();
        }
        public OnYourWayHomeApplication(Type hostType)
        {
            Requires.NotNull(hostType, "hostType");

            var conventions = new ConventionBuilder();

            conventions.ForTypesMatching(t => IsAPart(t)).Export()
            .ExportInterfaces()
            .Shared();

            conventions.ForTypesDerivedFrom <NavigatableViewModel>().Export()
            .Shared(NavigatableViewModel.SharingBoundary);

            var assemblies = new[] { typeof(OnYourWayHomeApplication).GetTypeInfo().Assembly,
                                     hostType.GetTypeInfo().Assembly };

            var configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            _compositionHost = configuration.CreateContainer();
        }
Example #35
0
        /// <summary>
        /// Each time this is invoked, the search paths and patterns
        /// (built-in assemblies and directory paths + patterns) are
        /// searched to resolve matching components.  The results are
        /// cached and available in <see cref="FoundProviders">.
        /// </summary>
        protected virtual IEnumerable <TProv> FindProviders()
        {
            try
            {
                _logger.LogInformation("resolving providers");

                var conventions = new ConventionBuilder();
                // conventions.ForTypesDerivedFrom<TProv>()
                conventions.ForTypesMatching <TProv>(MatchProviderType)
                .Export <TProv>()
                .Shared();

                var existingPaths = _SearchPaths.Where(x => Directory.Exists(x));
                var configuration = new ContainerConfiguration()
                                    .WithAssemblies(_BuiltInAssemblies, conventions)
                                    .WithAssemblies(_SearchAssemblies, conventions)
                                    .WithAssembliesInPaths(existingPaths.ToArray(), conventions);

                if (_adapter != null)
                {
                    configuration.WithProvider(_adapter);
                }

                using (var container = configuration.CreateContainer())
                {
                    _foundProviders = container.GetExports <TProv>().ToArray();
                }

                return(_foundProviders);
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                Console.Error.WriteLine(">>>>>> Load Exceptions:");
                foreach (var lex in ex.LoaderExceptions)
                {
                    Console.Error.WriteLine(">>>>>> >>>>" + lex);
                }
                throw ex;
            }
        }
Example #36
0
        /// <summary>
        /// Each time this is invoked, the search paths and patterns
        /// (built-in assemblies and directory paths + patterns) are
        /// searched to resolve matching components.  The results are
        /// cached and available in <see cref="FoundProviders">.
        /// </summary>
        protected IEnumerable <TExt> FindProviders()
        {
            var conventions = new ConventionBuilder();

            // conventions.ForTypesDerivedFrom<TExt>()
            conventions.ForTypesMatching <TExt>(MatchProviderType)
            .Export <TExt>()
            .Shared();

            var existingPaths = _SearchPaths.Where(x => Directory.Exists(x));
            var configuration = new ContainerConfiguration()
                                .WithAssemblies(_BuiltInAssemblies, conventions)
                                .WithAssemblies(_SearchAssemblies, conventions)
                                .WithAssembliesInPaths(existingPaths.ToArray(), conventions);

            using (var container = configuration.CreateContainer())
            {
                _foundProviders = container.GetExports <TExt>().ToArray();
            }

            return(_foundProviders);
        }
        public void TypesMarkedWithEagerlyConstructedAttributeAreConstructedEagerly()
        {
            var conventions = new ConventionBuilder()
                .WithEagerConstructionSupport();

            conventions.ForTypesMatching(t => true).Export();

            var configuration = new ContainerConfiguration()
                .WithDefaultConventions(conventions)
                .WithPart<ConstructionFlag>()
                .WithPart<EagerPart>();

            var container = configuration.CreateContainer();

            var flag = container.GetExport<ConstructionFlag>();
            Assert.IsFalse(flag.WasConstructed);

            container.ConstructEagerParts();

            Assert.IsTrue(flag.WasConstructed);

            EagerPart stillExported;
            Assert.IsTrue(container.TryGetExport(out stillExported));
        }
Example #38
0
        private static void ConfigureMef()
        {
            var conventions = new ConventionBuilder();

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

            conventions.ForTypesMatching(x => x.Name.EndsWith("Service"))
                       .ExportInterfaces();

            ViewLocator.BuildMefConventions(conventions);

            var configuration = new ContainerConfiguration()
                .WithAssembly(typeof(App).GetTypeInfo().Assembly, conventions)
                .WithAssembly(typeof(LinquaLib).GetTypeInfo().Assembly, conventions)
                .WithAssembly(typeof(FrameworkUwp).GetTypeInfo().Assembly)
                .WithProvider(new DefaultExportDescriptorProvider());

            var container = configuration.CreateContainer();

            CompositionManager.Initialize(container);

            App.CompositionManager = CompositionManager.Current;
        }
        public static IDependencyResolver CreateWithDefaultConventions(Assembly[] appAssemblies)
        {
            var conventions = new ConventionBuilder();

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

            conventions.ForTypesMatching(t => t.Namespace != null && t.Namespace.EndsWith(".Parts"))
                .Export()
                .ExportInterfaces();

            var container = new ContainerConfiguration()
                .WithAssemblies(appAssemblies, conventions)
                .CreateContainer();

            return new MefDependencyResolver(container);
        }
Example #40
0
 public void ExportSelectorNull_ShouldThrowArgumentNull()
 {
     var builder = new ConventionBuilder();
     ExceptionAssert.ThrowsArgumentNull("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null));
     ExceptionAssert.ThrowsArgumentNull("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null, null));
     ExceptionAssert.ThrowsArgumentNull("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null));
     ExceptionAssert.ThrowsArgumentNull("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null, null));
 }
        public void StandardExportInterfacesInterfaceFilterConfiguredContractShouldWork()
        {
            //Same test as above only using default export builder
            var builder = new ConventionBuilder();
            builder.ForTypesMatching((t) => true).ExportInterfaces((iface) => iface != typeof(System.IDisposable), (iface, bldr) => bldr.AsContractType((Type)iface));
            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);
        }
Example #42
0
        public void ConstructorSelectorNull_ShouldThrowArgumentNull()
        {
            var builder = new ConventionBuilder();

            AssertExtensions.Throws <ArgumentNullException>("constructorSelector", () => builder.ForTypesMatching <IFoo>((t) => true).SelectConstructor(null));
            AssertExtensions.Throws <ArgumentNullException>("importConfiguration", () => builder.ForTypesMatching <IFoo>((t) => true).SelectConstructor(null, null));
        }
Example #43
0
 public void ConstructorSelectorNull_ShouldThrowArgumentNull()
 {
     var builder = new ConventionBuilder();
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("constructorSelector", () => builder.ForTypesMatching<IFoo>((t) => true).SelectConstructor(null));
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("importConfiguration", () => builder.ForTypesMatching<IFoo>((t) => true).SelectConstructor(null, null));
 }
Example #44
0
 public void ExportSelectorNull_ShouldThrowArgumentNull()
 {
     var builder = new ConventionBuilder();
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty(null));
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty(null, null));
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty<IFirst>(null));
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("propertySelector", () => builder.ForTypesMatching<IFoo>((t) => true).ExportProperty<IFirst>(null, null));
 }
Example #45
0
 public void ExportInterfaceSelectorNull_ShouldThrowArgumentNull()
 {
     var builder = new ConventionBuilder();
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null));
     ExceptionAssert.ThrownMessageContains<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null, null));
 }
Example #46
0
        public void NotifyImportsSatisfiedPropertiesAndFields_ShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied5" || mi.Name == "OnImportsSatisfied6");
            var container = new ContainerConfiguration()
                .WithPart<OnImportsSatisfiedTestClassPropertiesAndFields>(builder)
                .WithPart<ExportValues>(builder)
                .CreateContainer();
            var test = container.GetExport<OnImportsSatisfiedTestClassPropertiesAndFields>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(0, test.OnImportsSatisfiedInvoked);
        }
Example #47
0
        public void NotifyImportsSatisfiedTwice_ShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied1" || mi.Name == "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);
        }
Example #48
0
        public void NotifyImportsSatisfiedAttributeAppliedToBaseClass_ShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesMatching(t => true).NotifyImportsSatisfied(mi => mi.Name == "OnImportsSatisfied");
            var container = new ContainerConfiguration()
                .WithPart<OnImportsSatisfiedDerivedClass>(builder)
                .WithPart<ExportValues>(builder)
                .CreateContainer();
            var test = container.GetExport<OnImportsSatisfiedDerivedClass>();

            Assert.NotNull(test.P1);
            Assert.NotNull(test.P2);
            Assert.Equal(1, test.OnImportsSatisfiedInvoked);
        }
Example #49
0
        public void InsideTheLambdaCallGetCustomAttributesShouldSucceed()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesMatching((t) => !t.GetTypeInfo().IsDefined(typeof(MyDoNotIncludeAttribute), false)).Export();
            var container = new ContainerConfiguration()
                .WithPart<MyNotToBeIncludedClass>(builder)
                .WithPart<MyToBeIncludedClass>(builder)
                .CreateContainer();

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

            Assert.Null(importer.MyNotToBeIncludedClass);
            Assert.NotNull(importer.MyToBeIncludedClass);
        }