public static void ConfigureHostingRegistrationBuilder(RegistrationBuilder builder)
        {
            builder.ForTypesDerivedFrom<IReplCommandWithInfo>().Export<IReplCommand>();
            builder.ForTypesDerivedFrom<ILineProcessor>().Export<ILineProcessor>();

            builder.ForType<ReplLogger>().SelectConstructor(b => b.First(c => c.GetParameters().Length == 1)).Export<ILog>();
            builder.ForType<FileSystem>().Export<IFileSystem>();
            builder.ForType<ReplScriptHostFactory>().Export<IScriptHostFactory>();
            builder.ForType<RoslynScriptEngine>().Export<IScriptEngine>();
            builder.ForType<FilePreProcessor>().Export<IFilePreProcessor>();

            builder.ForType<PackageContainer>().Export<IPackageContainer>();
            builder.ForType<PackageAssemblyResolver>().Export<IPackageAssemblyResolver>();
            builder.ForType<NugetInstallationProvider>().Export<IInstallationProvider>();
            builder.ForType<PackageInstaller>().Export<IPackageInstaller>();

            builder.ForType<ScriptPackResolver>().Export<IScriptPackResolver>();
            builder.ForType<AssemblyUtility>().Export<IAssemblyUtility>();
            builder.ForType<AssemblyResolver>().Export<IAssemblyResolver>();
            builder.ForType<ObjectSerializer>().Export<IObjectSerializer>();
            builder.ForType<MockConsole>().Export<IConsole>();

            builder.ForType<ScriptExecutor>().Export<IScriptExecutor>();
            builder.ForType<ScriptServices>().Export<ScriptServices>();

            builder.ForType<ReplExecutorFactory>().Export<IReplExecutorFactory>();
        }
Exemple #2
0
        private RegistrationBuilder GetConventions()
        {
            var builder = new RegistrationBuilder();

            builder.ForType <Config>()
            .SetCreationPolicy(CreationPolicy.Shared)
            .Export <IConfig>();
            builder.ForTypesDerivedFrom <ILogger>()
            .SetCreationPolicy(CreationPolicy.Shared)
            .Export <ILogger>();
            builder.ForTypesDerivedFrom <IEventBus>()
            .SetCreationPolicy(CreationPolicy.Shared)
            .Export <IEventBus>();
            builder.ForTypesDerivedFrom <IEventLoop>()
            .SetCreationPolicy(CreationPolicy.Shared)
            .Export <IEventLoop>();
            builder.ForType <TaskManager>()
            .SetCreationPolicy(CreationPolicy.Shared)
            .Export <ITaskManager>();
            builder.ForTypesDerivedFrom <ITask>()
            .Export <ITask>(b =>
                            b.AddMetadata(TaskManager.TaskNameMetadataKey, t => new TaskMetadata(t.Name))
                            );
            builder.ForTypesDerivedFrom <IShellCommand>()
            .Export <IShellCommand>();

            return(builder);
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            VisualComposition.Trace += (sender, args) => Trace.WriteLine(args.Text);
            BindingErrorTracer.Start(BindingErrorCallback);

            var context = new RegistrationBuilder();

            // Visuals can't be singletons:
            context.ForTypesDerivedFrom <FrameworkElement>()?.SetCreationPolicy(CreationPolicy.NonShared);
            // To demonstrate the ImportExtension with value converters.
            context.ForTypesDerivedFrom <IValueConverter>()?.Export();
            try
            {
                _compositionHost.AddCatalog(new ApplicationCatalog(context));
            }
            catch (ReflectionTypeLoadException ex)
            {
                MessageBox.Show(ex.Message + "\n" + string.Join("\n", ex.LoaderExceptions.Select(le => le.Message)));
            }


            Resources.MergedDictionaries.Insert(0, WpfStyles.GetDefaultStyles().RegisterDefaultWindowStyle());
            Resources.MergedDictionaries.Add(DataTemplateManager.CreateDynamicDataTemplates(_compositionHost.Container));

            MainWindow = _compositionHost.GetExportedValue <MainWindow>();
            MainWindow.Show();
        }
        public static void ConfigureModuleRegistrationBuilder(RegistrationBuilder builder)
        {
            builder.ForTypesDerivedFrom<IReplCommand>()
                .Export<IReplCommand>();

            builder.ForTypesDerivedFrom<ILineProcessor>()
                .Export<ILineProcessor>();
        }
Exemple #5
0
        public static void RegisterCatalogs(ICollection <ComposablePartCatalog> catalogs)
        {
            var builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom <IService>().Export().ExportInterfaces();
            builder.ForTypesDerivedFrom <DbContext>().Export().SetCreationPolicy(CreationPolicy.NonShared);
            var catalog = new DirectoryCatalog(HttpContext.Current.Server.MapPath("~/bin"), "Sof*.dll", builder);

            catalogs.Add(catalog);
        }
        private static RegistrationBuilder CreateRegistrationContext()
        {
            Contract.Ensures(Contract.Result <RegistrationBuilder>() != null);

            var context = new RegistrationBuilder();

            context.ForTypesDerivedFrom <FrameworkElement>().SetCreationPolicy(CreationPolicy.NonShared);
            context.ForTypesDerivedFrom <object>().SelectConstructor(SelectConstructor);

            return(context);
        }
 /// <summary>
 /// Defines the MVC conventions.
 /// </summary>
 /// <param name="conventions">The conventions.</param>
 /// <returns>RegistrationBuilder.</returns>
 private RegistrationBuilder DefineMvcConventions(RegistrationBuilder conventions)
 {
     conventions.ForTypesDerivedFrom<IController>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     conventions.ForTypesDerivedFrom<FilterAttribute>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     conventions.ForTypesDerivedFrom<IModelBinder>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     return conventions;
 }
        private static void RegisterMappers(RegistrationBuilder rb)
        {
            rb.ForTypesDerivedFrom <IRecipeDisplayViewModelMapper>()
            .Export <IRecipeDisplayViewModelMapper>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <IRecipeEditViewModelMapper>()
            .Export <IRecipeEditViewModelMapper>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <IStyleDisplayViewModelMapper>()
            .Export <IStyleDisplayViewModelMapper>()
            .SetCreationPolicy(CreationPolicy.NonShared);
        }
        private static void RegisterMappers(RegistrationBuilder rb)
        {
            rb.ForTypesDerivedFrom<IRecipeDisplayViewModelMapper>()
                .Export<IRecipeDisplayViewModelMapper>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<IRecipeEditViewModelMapper>()
                .Export<IRecipeEditViewModelMapper>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<IStyleDisplayViewModelMapper>()
                .Export<IStyleDisplayViewModelMapper>()
                .SetCreationPolicy(CreationPolicy.NonShared);
        }
        internal static RegistrationBuilder GetMvcConventions()
        {
            var conventions = new RegistrationBuilder();

            AddComponentsDerivedFromMyHerbalife3Interfaces(conventions);

            conventions.ForTypesDerivedFrom <IController>().Export().SetCreationPolicy(CreationPolicy.NonShared);

            conventions.ForTypesDerivedFrom <System.Web.Mvc.ActionFilterAttribute>()
            .Export()
            .SetCreationPolicy(CreationPolicy.NonShared);

            return(conventions);
        }
 /// <summary>
 /// Defines the default conventions for part composition.
 /// </summary>
 /// <returns>ReflectionContext.</returns>
 protected override RegistrationBuilder DefineConventions(RegistrationBuilder conventions = null)
 {
     conventions = base.DefineConventions(conventions);
     conventions.ForTypesDerivedFrom<IController>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     conventions.ForTypesDerivedFrom<FilterAttribute>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     conventions.ForTypesDerivedFrom<IModelBinder>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     return conventions;
 }
Exemple #12
0
        private static CompositionContainer ComposeHost()
        {
            var builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom <IGame>().Export <IGame>();
            builder.ForType <GameLoader>().Export();

            //Export types matching
            //builder.ForTypesMatching(x => x.Name.EndsWith("Game")).Export();

            var aggregateCatalog = new AggregateCatalog();

            //aggregateCatalog.Catalogs.Add(new DirectoryCatalog("Target", builder));

            aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly, builder));

            //aggregateCatalog.Catalogs.Add(new DirectoryCatalog(@"C:\Users\RConnolly\Google Drive\dev\ConsoleCade\TestGame\bin\Debug"));
            //aggregateCatalog.Catalogs.Add(new DirectoryCatalog(@"C:\Users\RConnolly\Google Drive\dev\ConsoleCade\TestGame2\bin\Debug"));

            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(Path.GetFullPath(@"..\..\Games")));

            var container = new CompositionContainer(aggregateCatalog);

            return(container);
        }
Exemple #13
0
        static void Main(string[] args)
        {
            var builder = new RegistrationBuilder();

            builder
            .ForTypesDerivedFrom <IPlugin>()
            .Export <IPlugin>();
            builder
            .ForType <PluginStore>()
            .Export()
            .ImportProperties(
                propertyFilter => true,
                (propertyInfo, importBuilder) => {
                importBuilder.AsMany();
            }
                );

            var catalog = new AssemblyCatalog(typeof(PluginStore).Assembly, builder);

            using (var container = new CompositionContainer(catalog)) {
                var pluginManager = container.GetExport <PluginStore>().Value;

                foreach (var plugn in pluginManager.Plugins)
                {
                    Console.WriteLine("{0}, {1}", plugn.Metadata.Name, plugn.Metadata.Version);
                    plugn.Value.Run();
                }
            }
        }
            public void Configuration(IAppBuilder app)
            {
                // Setup dependency injection
                var registrationBuilder = new RegistrationBuilder();

                registrationBuilder.ForTypesDerivedFrom <ApiController>().Export().SetCreationPolicy(CreationPolicy.NonShared);
                var catalog   = new AssemblyCatalog(typeof(ProductsController).Assembly, registrationBuilder);
                var container = new CompositionContainer(catalog, true);

                container.ComposeExportedValue <IProductTable>(new StubIProductTable
                {
                    GetAllProductsAsync = () => Task.FromResult <IEnumerable <Product> >(new[]
                    {
                        new Product {
                            ProductId = 1, Description = "Dummy", UnitPrice = 10M
                        }
                    })
                });

                // Enable Web API
                var configuration = new HttpConfiguration();

                configuration.DependencyResolver = new MefDependencyResolver(container);
                configuration.MapHttpAttributeRoutes();
                app.UseWebApi(configuration);
            }
Exemple #15
0
        public PluginContainer()
        {
            var registration = new RegistrationBuilder();

            registration.ForTypesDerivedFrom<BasicPlugin>()
                .SetCreationPolicy(CreationPolicy.Shared)
                .Export<BasicPlugin>();

            bool tryAgain = true;

            while (tryAgain)
            {
                try
                {
                    DirectoryCatalog dircat = new DirectoryCatalog(PluginDirectory, registration);
                    tryAgain = false;

                    Container = new CompositionContainer(dircat, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);
                    Container.ComposeParts();
                }
                catch (DirectoryNotFoundException)
                {
                    Directory.CreateDirectory(PluginDirectory);
                }
            }
        }
        public void MapType_OverridingSelectionOfConventionSelectedConstructor()
        {
            var builder = new RegistrationBuilder();

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

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

            var projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo());
            var projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo().GetTypeInfo());

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


            // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
            var typeLevelAttrs = projectedType2.GetCustomAttributes(false);

            Assert.AreEqual(0, constructor1.GetCustomAttributes(false).Length);
            Assert.AreEqual(0, constructor3.GetCustomAttributes(false).Length);

            var ci    = constructor2;
            var attrs = ci.GetCustomAttributes(false);

            Assert.AreEqual(1, attrs.Length);
            Assert.AreEqual(typeof(ImportingConstructorAttribute), attrs[0].GetType());
        }
        static void SetupMediator(RegistrationBuilder rb) {
            rb.ForType<Mediator>()
                .Export<IMediator>();

            rb.ForTypesDerivedFrom(typeof (IAsyncRequestHandler<,>))
                .ExportInterfaces();

            rb.ForTypesDerivedFrom(typeof (INotificationHandler<>))
                .ExportInterfaces();

            rb.ForTypesDerivedFrom(typeof (IAsyncNotificationHandler<>))
                .ExportInterfaces();

            rb.ForTypesDerivedFrom(typeof (IRequestHandler<,>))
                .ExportInterfaces();
        }
        /// <summary>
        /// 基于约定的部件注册
        /// </summary>
        /// <param name="path"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool FindEx(string path, MyCal obj)
        {
            var res = false;
            var rb  = new RegistrationBuilder();                         //用于定义出口和入口的约定

            rb.ForTypesDerivedFrom <ICalShow>().Export <ICalShow>();     //指定出口约定  给所有实现接口的类型应用[Export(Type)]特性
            rb.ForType <MyCal>().ImportProperty <ICalShow>(t => t.Show); //指定入口约定 将入口映射到指定的属性上
            var dc = new DirectoryCatalog(path, rb);
            CompositionService sv = dc.CreateCompositionService();

            try
            {
                sv.SatisfyImportsOnce(obj, rb); //在目录中搜索部件 多个出口匹配项出异常
                res = true;
            }
            catch (ChangeRejectedException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (CompositionException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            sv.Dispose();
            return(res);
        }
 /// <summary>
 /// Registers the dependencies (via convention) within this application.
 /// </summary>
 /// <param name="registrations">The dependency registrations/conventions to wire up.</param>
 /// <param name="catalog">An AggregateCatalog that can be added to if dependencies reside in an external assembly, i.e. BCL.</param>
 public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesDerivedFrom<ILogger>()
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
 }
        public void DiscoverServices(IServicePool pool)
        {
            var registration = new RegistrationBuilder();

            registration.ForTypesDerivedFrom<IService>().SelectConstructor((ConstructorInfo[] cInfo) =>
            {
                if (cInfo.Length == 0)
                    return null;
                return cInfo[0];
            }).Export<IService>();

            var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var catalog = new DirectoryCatalog(path, registration);
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            var services = container.GetExportedValues<IService>();

            foreach (var service in services)
            {
                service.ServicePool = pool;
                var interfaces = service.GetType().GetInterfaces();
                Type interfaceType = null;
                foreach (var i in interfaces)
                {
                    var name = i.FullName;
                    if (!name.Contains("Contracts.IService") && !name.Contains("System."))
                    {
                        interfaceType = i;
                        break;
                    }
                }
                pool.AddService(interfaceType, service);
            }
        }
        /// <summary>
        /// 基于约定的部件注册 类T注册接口K
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="K"></typeparam>
        /// <param name="path"></param>
        /// <param name="obj"></param>
        /// <param name="propertyFilter"></param>
        /// <returns></returns>
        public static bool FindExt <T, K>(string path, T obj, Predicate <PropertyInfo> propertyFilter)
        {
            var res = false;
            var rb  = new RegistrationBuilder();               //用于定义出口和入口的约定

            rb.ForTypesDerivedFrom <K>().Export <K>();         //指定出口约定  给所有实现接口的类型应用[Export(Type)]特性
            rb.ForType <T>().ImportProperties(propertyFilter); //指定入口约定
            var dc = new DirectoryCatalog(path, rb);
            CompositionService sv = dc.CreateCompositionService();

            try
            {
                sv.SatisfyImportsOnce(obj, rb); //在目录中搜索部件 若存在多个出口匹配项则抛出出异常
                res = true;
            }
            catch (ChangeRejectedException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (CompositionException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            sv.Dispose();
            return(res);
        }
        public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT()
        {
            var builder = new RegistrationBuilder();

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

            builder.ForType <FooImplWithConstructors2>().
            SelectConstructor(param => new FooImplWithConstructors2(param.Import <IEnumerable <IFoo> >()));

            TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo());
            TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors2).GetTypeInfo().GetTypeInfo());

            ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single();
            ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single();
            ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single();

            // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
            var typeLevelAttrs = projectedType2.GetCustomAttributes(false);

            Assert.Equal(0, constructor1.GetCustomAttributes(false).Length);
            Assert.Equal(0, constructor3.GetCustomAttributes(false).Length);

            ConstructorInfo ci    = constructor2;
            var             attrs = ci.GetCustomAttributes(false);

            Assert.Equal(1, attrs.Length);
            Assert.IsType <ImportingConstructorAttribute>(attrs[0]);
        }
Exemple #23
0
        public static PluginManager GetInstance()
        {
            var builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom <IPlugin>().ExportInterfaces();
            builder.ForType <PluginManager>().Export <PluginManager>();

            var failed  = new List <string>();
            var self    = new AssemblyCatalog(typeof(PluginManager).Assembly, builder);
            var catalog = new AggregateCatalog(self);

            if (Directory.Exists(PluginPath))
            {
                foreach (string path in new DirectoryInfo(PluginPath).GetFiles().Select(p => p.FullName).Where(p => p.ToLower().EndsWith(".dll")))
                {
                    try
                    {
                        var assembly = System.Reflection.Assembly.LoadFile(path);
                        catalog.Catalogs.Add(new AssemblyCatalog(assembly, builder));
                    }
                    catch (Exception ex) when(ex is NotSupportedException || ex is BadImageFormatException)
                    {
                        failed.Add(Uri.UnescapeDataString(new Uri(Path.GetFullPath(PluginPath)).MakeRelativeUri(new Uri(path)).ToString().Replace('/', Path.DirectorySeparatorChar)));
                    }
                }
            }

            var container = new CompositionContainer(catalog);
            var manager   = container.GetExportedValue <PluginManager>();

            manager.FailedFiles = failed;
            return(manager);
        }
Exemple #24
0
        /// <summary>
        /// This Method allows for additional catalogs to be added to the main MEF catalog.
        /// This is so that the Client application can have other classes/plugins that needs to be instantiated by MEF.
        /// </summary>
        /// <param name="catalogParts"></param>
        /// <returns></returns>
        public static CompositionContainer Init(ICollection <ComposablePartCatalog> catalogParts)
        {
            AggregateCatalog catalog = new AggregateCatalog();

            RegistrationBuilder pluginBuilder = new RegistrationBuilder();

            pluginBuilder.ForTypesDerivedFrom <IPluginWinForms>()
            .Export()
            .ExportInterfaces();

            foreach (var assembly in AssemblyLoaderUtil.WinFormsPlugins)
            {
                AssemblyCatalog assemCatalog = new AssemblyCatalog(assembly, pluginBuilder);
                assemCatalog.FixCatalogForRegistrationBuilderBug();
                catalogParts.Add(assemCatalog);
            }
            //The plugin factory assembly
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(PluginFactory).Assembly));

            if (catalogParts != null)
            {
                foreach (var part in catalogParts)
                {
                    catalog.Catalogs.Add(part);
                }
            }

            CompositionContainer container = new CompositionContainer(catalog);

            return(container);
        }
        public void DiscoverServices(IServicePool pool)
        {
            var registration = new RegistrationBuilder();

            registration.ForTypesDerivedFrom <IService>().SelectConstructor((ConstructorInfo[] cInfo) =>
            {
                if (cInfo.Length == 0)
                {
                    return(null);
                }
                return(cInfo[0]);
            }).Export <IService>();

            var path      = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var catalog   = new DirectoryCatalog(path, registration);
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            var services  = container.GetExportedValues <IService>();

            foreach (var service in services)
            {
                service.ServicePool = pool;
                var  interfaces    = service.GetType().GetInterfaces();
                Type interfaceType = null;
                foreach (var i in interfaces)
                {
                    var name = i.FullName;
                    if (!name.Contains("Contracts.IService") && !name.Contains("System."))
                    {
                        interfaceType = i;
                        break;
                    }
                }
                pool.AddService(interfaceType, service);
            }
        }
Exemple #26
0
        public static PluginManager GetInstance()
        {
            var builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom <IPlugin>().ExportInterfaces();
            builder.ForType <PluginManager>().Export <PluginManager>();

            var self    = new AssemblyCatalog(typeof(PluginManager).Assembly, builder);
            var catalog = new AggregateCatalog(self);
            var failed  = new List <string>();

            if (Directory.Exists(PluginPath))
            {
                foreach (string path in Directory.EnumerateFiles(PluginPath, "*.dll", SearchOption.AllDirectories))
                {
                    try
                    {
                        var asm = Assembly.LoadFile(Path.GetFullPath(path));
                        catalog.Catalogs.Add(new AssemblyCatalog(asm, builder));
                    }
                    catch (Exception ex) when(ex is NotSupportedException || ex is BadImageFormatException)
                    {
                        failed.Add(path);
                    }
                }
            }

            var container = new CompositionContainer(catalog);
            var manager   = container.GetExportedValue <PluginManager>();

            manager.FailedFiles = failed;
            return(manager);
        }
        public IList<AssemblyCatalog> Register(RegistrationBuilder builder)
        {
            builder.ForType<CommandQueue>()
                .Export<ICommandQueue>()
                .SetCreationPolicy(CreationPolicy.Shared);

            builder.ForTypesDerivedFrom<IChatParser>()
                .Export<IChatParser>()
                .SelectConstructor(cinfo => cinfo[0]);

            builder.ForType<Config.Config>()
                .Export<IConfig>()
                .SetCreationPolicy(CreationPolicy.Shared);

            builder.ForType<DataSource>()
                .Export<IDataSource>()
                .SetCreationPolicy(CreationPolicy.Shared);

            builder.ForType<Log>()
                .Export<ILog>()
                .SetCreationPolicy(CreationPolicy.Shared);

            builder.ForType<TwitchApi>()
                .Export<ITwitchApi>()
                .SetCreationPolicy(CreationPolicy.Shared);

            var catalogs = new List<AssemblyCatalog>();

            catalogs.Add(new AssemblyCatalog(typeof(PluginStore).Assembly, builder));
            catalogs.Add(new AssemblyCatalog(typeof(IDataSource).Assembly, builder));
            catalogs.Add(new AssemblyCatalog(typeof(ILog).Assembly, builder));
            catalogs.Add(new AssemblyCatalog(typeof(ITwitchApi).Assembly, builder));
            catalogs.Add(new AssemblyCatalog(typeof(IConfig).Assembly, builder));
            return catalogs;
        }
Exemple #28
0
        private static void ConfigureContainer(out CompositionContainer container, out CompositionScopingService service)
        {
            var componentsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");

            var reg = new RegistrationBuilder();

            reg

            .ForTypesDerivedFrom <IController>()
            .AddMetadata(ExportScope.Key, TransactionScope.Id)
            .Export <IController>()
            .Export();

            var rootCatalog = new DirectoryCatalog(componentsFolder, reg);

            try
            {
                var mms = rootCatalog.DiscoverModules();
                service   = new CompositionScopingService(mms.Catalog, mms.ExplicitExports, new String[] { TransactionScope.Id });
                container = new CompositionContainer(mms.Catalog);
            }
            catch (ReflectionTypeLoadException rtle)
            {
                var sb = new StringBuilder();
                sb.Append(rtle.UnwindException() + "<br/><br/>");

                foreach (var e in rtle.LoaderExceptions)
                {
                    sb.Append(e.UnwindException() + "<br/><br/>");
                }

                throw new ReflectionTypeLoadException(rtle.Types, rtle.LoaderExceptions, sb.ToString());
            }
        }
Exemple #29
0
        public void Initialize(string pluginPath, params string[] searchPatterns)
        {
            PluginPath = pluginPath;

            // Use RegistrationBuilder to set up our MEF parts.
            var regBuilder = new RegistrationBuilder();

            regBuilder.ForTypesDerivedFrom <T>().Export <T>();

            var catalog = new AggregateCatalog();

            //catalog.Catalogs.Add(new AssemblyCatalog(typeof (RunnerBase<T>).Assembly, regBuilder));
            foreach (var searchPattern in searchPatterns)
            {
                var directoryCatalog = new DirectoryCatalog(pluginPath, searchPattern, regBuilder);
                catalog.Catalogs.Add(directoryCatalog);
                _directoryCatalogs.Add(directoryCatalog);
            }

            _container = new CompositionContainer(catalog);
            _container.ComposeExportedValue(_container);

            // Get our exports available to the rest of Program.
            Exports = GetExportedValues();
        }
 /// <summary>
 /// Defines the WebAPI conventions.
 /// </summary>
 /// <param name="conventions">The conventions.</param>
 /// <returns>RegistrationBuilder.</returns>
 private RegistrationBuilder DefineWebApiConventions(RegistrationBuilder conventions)
 {
     conventions.ForTypesDerivedFrom<IHttpController>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     return conventions;
 }
        /// <summary>
        /// Constructor legt Singleton-Instanz an und kann nur einmal aufgerufen werden.
        /// </summary>
        protected MefExporter()
        {
            var loRegistrationBuilder = new RegistrationBuilder();

            loRegistrationBuilder.ForTypesDerivedFrom <ISchedulerJob>().SetCreationPolicy(CreationPolicy.NonShared).Export <ISchedulerJob>();

            this.moDirectoryCatalog = new DirectoryCatalog(Constants.JobDirectory, loRegistrationBuilder);
            this.moContainer        = new CompositionContainer(this.moDirectoryCatalog);
        }
        public void ImplementsIFooWithExport_ShouldFindTwoParts()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForTypesDerivedFrom <IFoo>().Export();
            var catalog = new TypeCatalog(new[] { typeof(IFoo), typeof(FooImplementation1), typeof(FooImplementation2) }, ctx);

            Assert.True(catalog.Parts.Count() == 2);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyResolutionBootstrapper" /> class.
 /// </summary>
 public DependencyResolutionBootstrapper()
 {
     var conventions = new RegistrationBuilder();
         conventions.ForTypesDerivedFrom<IDependencyResolutionConfigurator>()
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
     this.catalog = new DirectoryCatalog($"{Assembly.GetExecutingAssembly().GetCodeBaseDirectory()}", AssemblyNamingConvention, conventions);
 }
        public void ComposeDependencies()
        {
            var dependencyBuilder = new RegistrationBuilder();

            dependencyBuilder.ForTypesDerivedFrom <IDeployAgent>()
            .Export <IDeployAgent>();
            dependencyBuilder.ForTypesDerivedFrom <IMruManager>()
            .Export <IMruManager>();
            dependencyBuilder.ForTypesDerivedFrom <IMainPageViewModel>()
            .Export <IMainPageViewModel>();
            dependencyBuilder.ForType <MainWindow>()
            .Export();

            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), dependencyBuilder);

            this.CompositionContainer = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);
            this.CompositionContainer.ComposeParts();
        }
Exemple #35
0
        void Run()
        {
            RegistrationBuilder builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom <ICarContract>()
            .Export <ICarContract>(eb =>
            {
                eb.AddMetadata("Name", t => { return((t == typeof(CarBMW)) ? "BMW" : "Mercedes"); });
                eb.AddMetadata("Price", t => { return((t == typeof(CarBMW)) ? (uint)51000 : (uint)48000); });
            })
            .SetCreationPolicy(CreationPolicy.NonShared);

            builder.ForType <CarHost>()
            .Export()
            .SelectConstructor(ctors => ctors.First(ci => ci.GetParameters().Length == 2), (pi, ib) => ib.AsMany(true))
            .SetCreationPolicy(CreationPolicy.NonShared);

            var catalog   = new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder);
            var container = new CompositionContainer(catalog);

            var carHost = container.GetExportedValue <CarHost>();

            Lazy <ICarContract, ICarMetadata>[] carPartsA = carHost.GetCarPartsA();
            Lazy <ICarContract, ICarMetadata>[] carPartsB = carHost.GetCarPartsB();

            Console.WriteLine("CarPart A:");
            foreach (Lazy <ICarContract, ICarMetadata> carPart in carPartsA)
            {
                Console.WriteLine(carPart.Value.DoSomething());
            }
            Console.WriteLine("");

            Console.WriteLine("CarPart B:");
            foreach (Lazy <ICarContract, ICarMetadata> carPart in carPartsB)
            {
                Console.WriteLine(carPart.Value.DoSomething());
            }
            Console.WriteLine("");

            Console.WriteLine("Metadata CarPart A: ");
            foreach (Lazy <ICarContract, ICarMetadata> carPart in carPartsA)
            {
                Console.WriteLine(carPart.Metadata.Name);
                Console.WriteLine(carPart.Metadata.Price);
            }
            Console.WriteLine("");

            Console.WriteLine("Metadata CarPart B: ");
            foreach (Lazy <ICarContract, ICarMetadata> carPart in carPartsB)
            {
                Console.WriteLine(carPart.Metadata.Name);
                Console.WriteLine(carPart.Metadata.Price);
            }

            Console.ReadLine();
        }
Exemple #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonMefPlugInCache"/> class.
 /// </summary>
 /// <param name="log">[Optional] The application log file to use.</param>
 public GorgonMefPlugInCache(IGorgonLog log = null)
 {
     _builder.ForTypesDerivedFrom <GorgonPlugIn>().Export <GorgonPlugIn>(b =>
     {
         b.AddMetadata("Name", t => t.FullName);
         b.AddMetadata("Assembly", t => t.Assembly.GetName());
         b.Inherited();
     });
     Log        = log ?? GorgonLog.NullLog;
     _container = new CompositionContainer(_rootCatalog, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);
 }
Exemple #37
0
        public static System.ComponentModel.Composition.Primitives.ComposablePartCatalog ComposeRegistrationForAssembly <TContract>(System.Reflection.Assembly assembly)
        {
            var registration = new RegistrationBuilder();

            registration.ForTypesDerivedFrom <TContract>()
            .Export <TContract>();

            var catalog = new AssemblyCatalog(assembly, registration);

            return(catalog);
        }
 /// <summary>
 /// Bootstraps the dependencies within this library.
 /// </summary>
 /// <param name="registrations">The dependency registrations/conventions to wire up.</param>
 /// <param name="catalog">An AggregateCatalog that can be added to if dependencies reside in an external assembly, i.e. BCL.</param>
 public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesMatching(t => t.Name.EndsWith("Repository"))
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
     registrations.ForTypesDerivedFrom<IConnectionFactory>()
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
 }
Exemple #39
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            BindingErrorTracer.Start(BindingErrorCallback);

            var context = new RegistrationBuilder();
            // Visuals can't be singletons:
            context.ForTypesDerivedFrom<FrameworkElement>().SetCreationPolicy(CreationPolicy.NonShared);
            // To demonstrate the ImportExtension with value converters.
            context.ForTypesDerivedFrom<IValueConverter>().Export();

            _compositionHost.AddCatalog(new ApplicationCatalog(context));

            var dataTemplateResources = DataTemplateManager.CreateDynamicDataTemplates(_compositionHost.Container);
            Resources.MergedDictionaries.Add(dataTemplateResources);

            MainWindow = _compositionHost.GetExportedValue<MainWindow>();
            MainWindow.Show();
        }
Exemple #40
0
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">
        /// The args. 
        /// </param>
        public static void Main(string[] args)
        {
            WriteSignature();

            using (AggregateCatalog aggregateCatalog = new AggregateCatalog())
            {
                RegistrationBuilder registrationBuilder = new RegistrationBuilder();

                registrationBuilder.ForTypesDerivedFrom<ICommand>()
                                   .Export(conf => conf.AsContractName(AttributedModelServices.GetContractName(typeof(ICommand))))
                                   .SetCreationPolicy(CreationPolicy.NonShared);
                
                aggregateCatalog.Catalogs.Add(new ApplicationCatalog(registrationBuilder));

                string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginPath = Path.Combine(appPath, "plugins");
                if (Directory.Exists(pluginPath))
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(pluginPath, registrationBuilder));

                using (CompositionContainer container = new CompositionContainer(aggregateCatalog))
                {
                    ICommandProvider[] providers = container.GetExports<ICommandProvider>().Select(l => l.Value).ToArray();
                    Type[] commands = providers.SelectMany(p => p.GetCommands()).ToArray();

                    Func<Type, object> mefActivator =
                        t =>
                        {
                            if (!typeof(ICommand).IsAssignableFrom(t))
                                return DefaultActivator.Instance.CreateInstance(t);

                            ImportDefinition importDefinition = new ImportDefinition(ed => (string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName] == AttributedModelServices.GetTypeIdentity(t),
                                                                                     AttributedModelServices.GetContractName(typeof(ICommand)),
                                                                                     ImportCardinality.ExactlyOne,
                                                                                     false,
                                                                                     true);

                            return container.GetExports(importDefinition).First().Value;
                        };

                    ArgumentParserSettings parserSettings = new ArgumentParserSettings
                                                            {
                                                                TypeActivator = new DelegateActivator(mefActivator)
                                                            };

                    ArgumentParser<ICommand> argumentParser = new ArgumentParser<ICommand>(parserSettings, commands);
                    ICommand command;
                    if (argumentParser.TryParse(args, out command))
                    {
                        command.Invoke(container);
                    }
                }
            }
        }
Exemple #41
0
        private DirectoryCatalog GetExecutionDirectoryCatalog()
        {
            //This registration makes it easier to implement new bots, because you won't have to put in the [Export(...)] attribute.
            var Registration = new RegistrationBuilder();

            Registration
                .ForTypesDerivedFrom<IHero>()
                .Export<IHero>();

            var ExecutionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            return new DirectoryCatalog(ExecutionPath, Registration);
        }
 /// <summary>
 /// Adds necessary composition registrations to perform composition for WebAPI.
 /// </summary>
 /// <param name="registrations">The dependency registrations/conventions to wire up.</param>
 /// <param name="catalog">An AggregateCatalog that can be added to if dependencies reside in an external assembly, i.e. BCL.</param>
 public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesDerivedFrom<IHttpController>()
         .SetCreationPolicy(CreationPolicy.NonShared)
         .Export();
     registrations.ForTypesMatching(t => t.GetInterfaces().Contains(typeof(IHttpRouteConstraint)) &&
                                         t.Name.EndsWith("RouteConstraint"))
         .AddMetadata(Constants.ApplicationScoped, true)
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export(x => x.AddMetadata("ConstraintName", t => t.Name.Replace("RouteConstraint", "")));
     registrations.ForTypesDerivedFrom<IInlineConstraintResolver>()
         .AddMetadata(Constants.ApplicationScoped, true)
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
     registrations.ForType<HeliarModelBinderProvider>()
         .AddMetadata(Constants.ApplicationScoped, true)
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
 }
        private static void RegisterRepositories(RegistrationBuilder rb)
        {
            rb.ForTypesDerivedFrom <IRecipeRepository>()
            .Export <IRecipeRepository>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <IStyleRepository>()
            .Export <IStyleRepository>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <IReviewRepository>()
            .Export <IReviewRepository>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <IUserProfileRepository>()
            .Export <IUserProfileRepository>()
            .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom <ILibraryRepository>()
            .Export <ILibraryRepository>()
            .SetCreationPolicy(CreationPolicy.NonShared);
        }
        public void Support_custom_reflection_context_for_using_MEF_conventions()
        {
            using (var sut = new PackageContainer <IDisposable>())
            {
                sut.Conventions.Should().BeNull();

                var conventions = new RegistrationBuilder();
                conventions.ForTypesDerivedFrom <IDisposable>()
                .ExportInterfaces();

                sut.Conventions = conventions;
                sut.Conventions.Should().Be(conventions);
            }
        }
Exemple #45
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            BindingErrorTracer.Start(BindingErrorCallback);

            var context = new RegistrationBuilder();

            // Visuals can't be singletons:
            context.ForTypesDerivedFrom <FrameworkElement>()?.SetCreationPolicy(CreationPolicy.NonShared);
            // To demonstrate the ImportExtension with value converters.
            context.ForTypesDerivedFrom <IValueConverter>()?.Export();
            _compositionHost.AddCatalog(new ApplicationCatalog(context));

            var dataTemplateResources = DataTemplateManager.CreateDynamicDataTemplates(_compositionHost.Container);

            Resources.MergedDictionaries.Add(dataTemplateResources);

            Resources.MergedDictionaries.Insert(0, WpfStyles.Defaults());

            MainWindow = _compositionHost.GetExportedValue <MainWindow>();
            MainWindow.Show();
        }
Exemple #46
0
        public Runner()
        {
            // Use RegistrationBuilder to set up our MEF parts.
            var regBuilder = new RegistrationBuilder();
            regBuilder.ForTypesDerivedFrom<IExport>().Export<IExport>();

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Runner).Assembly, regBuilder));
            directoryCatalog = new DirectoryCatalog(pluginPath, regBuilder);
            catalog.Catalogs.Add(directoryCatalog);

            container = new CompositionContainer(catalog);
            container.ComposeExportedValue(container);
            Recompose();
        }
Exemple #47
0
        public void Run()
        {
            var conventions = new RegistrationBuilder();

            conventions.ForTypesDerivedFrom <ICalculator>().Export <ICalculator>();
            conventions.ForType <Program>().ImportProperty <ICalculator>(p => p.Calculator);
            var catalog = new DirectoryCatalog(Settings.Default.AddInDirectory, conventions);

            using (CompositionService service = catalog.CreateCompositionService())
            {
                service.SatisfyImportsOnce(this, conventions);
            }

            CalculatorLoop();
        }
        public void ExportInheritedInterfaceWithImplements2()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForTypesDerivedFrom(typeof(IFoo)).Export((c) => c.Inherited().AsContractType(typeof(IFoo)));
            var catalog = new TypeCatalog(new[] { typeof(CFoo) }, ctx);

            Assert.True(catalog.Parts.Count() != 0);

            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            var importer  = new FooImporter();

            container.SatisfyImportsOnce(importer);

            Assert.True(importer.fooImporter != null, "fooImporter not set!");
        }
        public void DoWorkInShadowCopiedDomain()
        {
            // Use RegistrationBuilder to set up our MEF parts.
            var regBuilder = new RegistrationBuilder();
            regBuilder.ForTypesDerivedFrom<IExport>().Export<IExport>();

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Runner).Assembly, regBuilder));
            directoryCatalog = new DirectoryCatalog(pluginPath, regBuilder);
            catalog.Catalogs.Add(directoryCatalog);

            container = new CompositionContainer(catalog);
            container.ComposeExportedValue(container);

            // Get our exports available to the rest of Program.
            exports = container.GetExportedValues<IExport>();
            Console.WriteLine("{0} exports in AppDomain {1}", exports.Count(), AppDomain.CurrentDomain.FriendlyName);
        }
Exemple #50
0
        public static CompositionContainer InitializePluginStoreNew(Func<RegistrationBuilder, ComposablePartCatalog> addAssemblies = null)
        {
            var setupBuilder = new RegistrationBuilder();
            ComposablePartCatalog setupCatalog = null;
            if (addAssemblies == null)
            {
                setupCatalog = new DirectoryCatalog(".", setupBuilder);
            }
            else
            {
                setupCatalog = addAssemblies(setupBuilder);
            }

            setupBuilder.ForTypesDerivedFrom<IPluginRegister>()
                .Export<IPluginRegister>()
                .SelectConstructor(cinfo => cinfo[0]);

            var setupContainer = new CompositionContainer(setupCatalog);

            var aggregateCatalog = new AggregateCatalog();
            var allCatalogs = new Dictionary<string, AssemblyCatalog>();
            var mainBuilder= new RegistrationBuilder();
            foreach (var register in setupContainer.GetExports<IPluginRegister>())
            {
                foreach (var catalog in register.Value.Register(mainBuilder))
                {
                    if (!allCatalogs.ContainsKey(catalog.Assembly.FullName))
                    {
                        allCatalogs.Add(catalog.Assembly.FullName, catalog);
                    }
                }
            }

            foreach (var cat in allCatalogs)
            {
                aggregateCatalog.Catalogs.Add(cat.Value);
            }

            Container = new CompositionContainer(aggregateCatalog);

            return setupContainer;
        }
        private static void RegisterRepositories(RegistrationBuilder rb)
        {
            rb.ForTypesDerivedFrom<IRecipeRepository>()
                .Export<IRecipeRepository>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<IStyleRepository>()
                .Export<IStyleRepository>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<IReviewRepository>()
                .Export<IReviewRepository>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<IUserProfileRepository>()
                .Export<IUserProfileRepository>()
                .SetCreationPolicy(CreationPolicy.NonShared);

            rb.ForTypesDerivedFrom<ILibraryRepository>()
                .Export<ILibraryRepository>()
                .SetCreationPolicy(CreationPolicy.NonShared);
        }
        public ControllerServiceResolver()
        {
            // Create MEF catalog based on existing exports and convention model
             var registration = new RegistrationBuilder();

             registration.ForTypesDerivedFrom<Controller>().SetCreationPolicy(CreationPolicy.NonShared).Export();

             //registration.ForTypesMatching(t => t.FullName.StartsWith(Assembly.GetExecutingAssembly().GetName().Name + ".Parts."))
             //   .SetCreationPolicy(CreationPolicy.NonShared)
             //   .ExportInterfaces(x => x.IsPublic);

             //var filteredCatalog = new FilteringCatalog(defaultCatalog,
             //   def => !def.Metadata.ContainsKey("ServiceType") || string.Equals((string)def.Metadata["ServiceType"], "...", StringComparison.OrdinalIgnoreCase));

             var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), registration);
             var defaults = new CatalogExportProvider(new TypeCatalog(DefaultGalleryServiceType));

             Container = new CompositionContainer(catalog, defaults);

             defaults.SourceProvider = Container;

             Container.ComposeParts(this);
        }
Exemple #53
0
        /// <summary>
        /// Loads the logger factories.
        /// </summary>
        private void LoadFactories()
        {
            var conventions = new RegistrationBuilder();

            //search for ILoggerFactory implementations
            conventions
                .ForTypesDerivedFrom<ILoggerFactory>()
                .Export<ILoggerFactory>();

            //search for IAuthenticatorFactory implementations
            conventions
                .ForTypesDerivedFrom<IAuthenticatorFactory>()
                .Export<IAuthenticatorFactory>();

            //search for ISerializerFactory implementations
            conventions
                .ForTypesDerivedFrom<ITypeFactory>()
                .Export<ITypeFactory>();

            //import into LoggerFactories
            conventions
                .ForType<Loader>()
                .ImportProperty(extensions => extensions.LoggerFactories);

            //import into AuthenticationFactories
            conventions
                .ForType<Loader>()
                .ImportProperty(extensions => extensions.AuthenticationFactories);

            //import into AuthenticationFactories
            conventions
                .ForType<Loader>()
                .ImportProperty(extensions => extensions.TypeFactories);

            //create catalog of dlls
            var catalog = new AggregateCatalog();

            //go and search for ILoggerFactories in executing directory
            string path = AppDomain.CurrentDomain.BaseDirectory;
            catalog.Catalogs.Add(new DirectoryCatalog(path, conventions));

            string subPath = AppDomain.CurrentDomain.RelativeSearchPath;

            //or in bin directory (asp.net)
            if(!string.IsNullOrEmpty(subPath) && Directory.Exists(subPath))
                catalog.Catalogs.Add(new DirectoryCatalog(subPath, conventions));

            //create container
            var container = new CompositionContainer(catalog, CompositionOptions.Default);

            try
            {
                //get me my factories 
                container.SatisfyImportsOnce(this, conventions);
            }
            catch
            {
                //in case of any loading errors, load only the loggers and authenticators, and serializers that we implement
                LoggerFactories = new List<ILoggerFactory>
                {
                    new NullLoggerFactory(),
                    new ConsoleLoggerFactory(),
                    new DebugLoggerFactory(),
                    new TraceLoggerFactory()
                };

                AuthenticationFactories = new List<IAuthenticatorFactory>
                {
                    new PasswordAuthenticatorFactory()
                };

                TypeFactories = new List<ITypeFactory>
                {
                    new AsciiTypeFactory(),
                    new BooleanTypeFactory(),
                    new BytesTypeFactory(),
                    new CounterColumnTypeFactory(),
                    new DateTypeFactory(),
                    new DecimalTypeFactory(),
                    new DoubleTypeFactory(),
                    new FloatTypeFactory(),
                    new InetAddressTypeFactory(),
                    new Int32TypeFactory(),
                    new IntegerTypeFactory(),
                    new LexicalUUIDTypeFactory(),
                    new ListTypeFactory(),
                    new LongTypeFactory(),
                    new MapTypeFactory(),
                    new SetTypeFactory(),
                    new TimestampTypeFactory(),
                    new TimeUUIDTypeFactory(),
                    new UTF8TypeFactory(),
                    new UUIDTypeFactory()
                };
            }
        }
        /// <summary>
        /// By default, we are configured to use MEF
        /// </summary>
        protected override void Configure()
        {
            var exeDir = Assembly.GetExecutingAssembly().Location;

            //setup catalog with core assemblies
            var aggregateCatalog = new AggregateCatalog(
                new AssemblyCatalog(GetType().Assembly), //CShell
                new AssemblyCatalog(typeof(IShell).Assembly) //CShell.Core
                );

            //load modules
            var moduleBuilder = new RegistrationBuilder();
            moduleBuilder.ForTypesDerivedFrom<IModule>().Export<IModule>();
            HostingHelpers.ConfigureModuleRegistrationBuilder(moduleBuilder);

            var modulesDir = Path.Combine(exeDir, Constants.CShellModulesPath);
            if (Directory.Exists(modulesDir))
            {
                var directories = Directory.GetDirectories(modulesDir).ToList();
                directories.Add(modulesDir);
                foreach (var dir in directories)
                {
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(dir, moduleBuilder));
                }
            }

            //make module assemblies available to caliburn.micro
            AssemblySource.Instance.AddRange(
                aggregateCatalog.Parts
                    .AsParallel()
                    .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
                    .Distinct()
                    .ToList()
                    .Where(assembly => !AssemblySource.Instance.Contains(assembly)));

            //setup ScriptCS hosting
            HostingHelpers.ConfigureHostingCatalog(aggregateCatalog);

            //setup the container
            container = new CompositionContainer(aggregateCatalog);
            //add custom exports
            var batch = new CompositionBatch();
            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(container);
            container.Compose(batch);

            //configure the modules
            modules = container.GetExportedValues<IModule>().ToList();
            foreach (var module in modules.OrderBy(m => m.Order))
            {
                var moduleConfiguration = new ModuleConfiguration(new CompositionBatch());
                module.Configure(moduleConfiguration);
                //see if we should update the DI container
                if(moduleConfiguration.CompositionBatch.PartsToAdd.Count > 0 || moduleConfiguration.CompositionBatch.PartsToRemove.Count > 0)
                    container.Compose(batch);
            }
        }
 public void BootstrappingUsingCatalogAndConventionShouldIncludeTestAndSampleParts()
 {
     // Build pre-wired assembly catalog
     RegistrationBuilder conventions = new RegistrationBuilder();
     conventions.ForTypesDerivedFrom<IApplicationDependencyRegistrar>()
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
     var catalog = new AssemblyCatalog(typeof(ContainerBootstrapperTest).Assembly, conventions);
     var sut = new ContainerBootstrapper("Samples*.dll", catalog);
     sut.Should().NotBeNull();
     var result = sut.Bootstrap();
     result.Should().NotBeNull();
     result.Catalog.Should().NotBeNull();
     // Registrars
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Heliar.Composition.Core.Tests.TestApplicationDependencyRegistrar");
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Samples.Business.BusinessDependencyRegistrar");
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Samples.Data.DataDependencyRegistrar");
     // Test/Sample types
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Heliar.Composition.Core.Tests.Foo");
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Samples.Business.CustomerService");
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Samples.Data.CustomerRepository");
     result.Catalog.Parts.Should().Contain(p => (p as System.ComponentModel.Composition.Primitives.ICompositionElement).DisplayName == "Samples.Data.SampleConnectionFactory");
 }
Exemple #56
0
		public static void Main(string[] args) {
			MainWindow mainWindow=null;
		#if !DEBUG
			try {
		#endif
				// Pārslēdz kanālu citā programmas eksemplārā, ja tāds ir.
				Process thisProcess=Process.GetCurrentProcess();
				foreach (Process otherProcess in Process.GetProcessesByName(thisProcess.ProcessName)) {
					if (otherProcess.Id != thisProcess.Id) {
						if (args.Length == 1) {
							var radioSwitch=new ChannelFactory<IRadioSwitch>(
								new NetNamedPipeBinding() { OpenTimeout=TimeSpan.FromSeconds(10), SendTimeout=TimeSpan.FromSeconds(5) },
								RadioSwitch.ServiceUrl);
							try { radioSwitch.CreateChannel().SetChannel(args[0]); }
							catch {}
						} else SetForegroundWindow(otherProcess.MainWindowHandle);
						return;
					}
				}

				// Ielādē visas stacijas no programmas mapes un XML faila staciju.
				var registration=new RegistrationBuilder(); registration.ForTypesDerivedFrom<Station>().Export<Station>();
				var container=new CompositionContainer(new AggregateCatalog(new DirectoryCatalog(".", "*.Station.dll", registration), new TypeCatalog(typeof(RadioXmlStation))));
				// ! Pašlaik drīkst būt tikai viena stacijas klase katrā DLLā.
				var app=new RadioApp(container.GetExportedValues<Station>().ToDictionary(s => {
					string name=s.GetType().Assembly.GetName().Name.ToLower();
					if (name.Contains(RadioApp.ChannelIdSeparator)) return name.Substring(0, name.Length-8).Replace(RadioApp.ChannelIdSeparator, '_'); // -8 noņem vārdu "station".
					else return name;
				}));

				Settings settings=Settings.Default;
				Channel channel=null;
				// Palaiž programmu ar izvēlēto kanālu.
				if (args.Length == 1) channel=app.GetChannel(args[0]);
				else {
					try {
						channel=app.GetChannel(settings.ChannelId);
					} catch (ChannelNotFoundException) {
						// Pēc staciju nomaiņas saglabātais kanāls var būt nepareizs.
						settings.ChannelId=null;
					}
				}
				mainWindow=new MainWindow(channel);
				app.Run(mainWindow);

				if (!(mainWindow.Channel is EmptyChannel)) {
		#if !DEBUG
					// Saglabā pēdējo klausīto kanālu.
					settings.ChannelId=mainWindow.Channel.Id;
					settings.Volume=mainWindow.Channel.Volume;
		#endif
					mainWindow.Channel.Dispose();
				}
		#if !DEBUG
				bool saved=false;
				foreach (var station in app.Stations.Values)
					if (station.HasSettingsChanges) {
						station.SaveSettings();
						saved=true;
					}
				if (!saved && settings.HasChanges) settings.Save();
			} catch (Exception ex) { // Visaptverošs kļūdu uztvērējs, lai problēmu gadījumā neparādītos Windows Error Reporting logs.
				string channelId;
				if (mainWindow != null && mainWindow.Channel != null) {
					channelId=mainWindow.Channel.Id;
					try {
						mainWindow.Channel.Stop(); // Fona procesu likvidācijai.
					} catch {}
				} else channelId=null;
				if (!(ex is ChannelNotFoundException)) RadioApp.LogError(ex, channelId);
				RadioApp.ShowError(ex.Message, "Kļūda radio darbībā");
			}
		#endif
		}
        private static RegistrationBuilder CreateRegistrationContext()
        {
            Contract.Ensures(Contract.Result<RegistrationBuilder>() != null);

            var context = new RegistrationBuilder();
            context.ForTypesDerivedFrom<FrameworkElement>().SetCreationPolicy(CreationPolicy.NonShared);
            return context;
        }
 private void PrepMEF()
 {
     var RegBld = new RegistrationBuilder();
     RegBld.ForTypesDerivedFrom<IPlug>().Export<IPlug>();
     RegBld.ForType<MainVM>().Export().ImportProperties(pi => pi.Name=="InstalledPlugins", (pi, ib) =>
     {
         ib.AsMany();
         //ib.AllowDefault();
         ib.RequiredCreationPolicy(CreationPolicy.Shared);
     }).ImportProperties(pi => pi.Name == "PluginExports", (pi, ib) =>
     {
         ib.AsMany();
         //ib.AllowDefault();
         ib.RequiredCreationPolicy(CreationPolicy.Shared);
     });
     var catalog = new AggregateCatalog(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly(), RegBld));
     this.container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
 }
 static void SetupInfrastructure(RegistrationBuilder rb) {
     rb.ForTypesDerivedFrom<IInfrastructureService>()
         .ExportInterfaces();
 }
Exemple #60
0
        /// <summary>
        ///   Loads the logger factories.
        /// </summary>
        public void LoadLoggerFactories()
        {
            var conventions = new RegistrationBuilder();

            //search for ILoggerFactory implementations
            conventions
                .ForTypesDerivedFrom<ILoggerFactory>()
                .Export<ILoggerFactory>();

            //inport into LoggerFactories
            conventions
                .ForType<LoggerManager>()
                .ImportProperty(manager => manager.LoggerFactories);

            //create catalog of dlls
            var catalog = new AggregateCatalog();

            //go and search for ILoggerFactories in executing directory
            string path = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
            catalog.Catalogs.Add(new DirectoryCatalog(path, conventions));

            //or in bin directory (asp.net)
            if (Directory.Exists(path + "\\bin"))
                catalog.Catalogs.Add(new DirectoryCatalog(path + "\\bin", conventions));

            //create container
            var container = new CompositionContainer(catalog, CompositionOptions.Default);

            try
            {
                //get me my factories
                container.SatisfyImportsOnce(this, conventions);
            }
            catch
            {
                //in case of any loading errors, assume no factories are loaded
                LoggerFactories = new List<ILoggerFactory>();
            }
        }