Esempio n. 1
0
        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;
        }
Esempio n. 2
0
        public async Task TestName()
        {
            var rb = new RegistrationBuilder();
            rb.ForType<ITaskAction>()
              .Export<TestTask>();
            rb.ForType<ParallelizeActionDecorator>()
              .Export<ParallelizeActionDecorator>();
            var tc = new TypeCatalog(new [] {typeof(ITaskAction),typeof(ParallelizeActionDecorator)},rb);

            var cc = new CompositionContainer(tc);
            var x = cc.GetExportedValue<ParallelizeActionDecorator>();
            await x.RunAction(CancellationToken.None);
        }
Esempio n. 3
0
        public void AfterResolvingAdapter_AddingMoreAdaptees_AddsMoreAdapters()
        {
            var registryBuilder = Factory.CreateEmptyComponentRegistryBuilder();

            registryBuilder.AddRegistrationSource(new MetaRegistrationSource());
            var metaService = new TypedService(typeof(Meta <object>));

            var first = RegistrationBuilder.ForType <object>().CreateRegistration();

            registryBuilder.Register(first);

            using (var container = new Container(registryBuilder.Build()))
            {
                var meta1 = container.ComponentRegistry.RegistrationsFor(metaService);
                Assert.Single(meta1);

                var second = RegistrationBuilder.ForType <object>().CreateRegistration();

                using (var lifetimeScope = container.BeginLifetimeScope(builder => builder.ComponentRegistryBuilder.Register(second)))
                {
                    var meta2 = lifetimeScope.ComponentRegistry.RegistrationsFor(metaService);

                    Assert.Equal(2, meta2.Count());
                }
            }
        }
Esempio n. 4
0
        /// <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);
        }
        /// <summary>
        /// Decorate all components implementing service <paramref name="serviceType"/>
        /// with decorator service <paramref name="decoratorType"/>.
        /// </summary>
        /// <param name="builder">Container builder.</param>
        /// <param name="decoratorType">Service type of the decorator. Must accept a parameter
        /// of type <paramref name="serviceType"/>, which will be set to the instance being decorated.</param>
        /// <param name="serviceType">Service type being decorated.</param>
        /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
        /// instance determines if the decorator should be applied.</param>
        public static void RegisterDecorator(
            this ContainerBuilder builder,
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType,
            Type serviceType,
            Func <IDecoratorContext, bool>?condition = null)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (decoratorType == null)
            {
                throw new ArgumentNullException(nameof(decoratorType));
            }

            if (serviceType == null)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }

            var decoratorService = new DecoratorService(serviceType, condition);

            var rb = RegistrationBuilder.ForType(decoratorType).As(decoratorService);

            var decoratorRegistration = rb.CreateRegistration();

            var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);

            builder.RegisterServiceMiddleware(serviceType, middleware, MiddlewareInsertionMode.StartOfPhase);

            // Add the decorator to the registry so the pipeline gets built.
            builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
        }
        private static IComponentRegistration CreateRegistrationForNonHistoryObject <T>(Service providedService)
        {
            var rb = RegistrationBuilder.ForType(typeof(ValueHistory <T>))
                     .As(providedService);

            return(RegistrationBuilder.CreateRegistration(rb));
        }
Esempio n. 7
0
 public IList<AssemblyCatalog> Register(RegistrationBuilder builder)
 {
     builder
         .ForType<StrawPoll>()
         .Export<IPoll>();
     return new List<AssemblyCatalog>() { new AssemblyCatalog(GetType().Assembly, builder)};
 }
Esempio n. 8
0
        /// <summary>
        /// 基于约定的部件注册
        /// </summary>
        /// <param name="path"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool FindEx(string path, MEFClient.MyCal obj)
        {
            var res = false;
            var rb  = new RegistrationBuilder();                                               //用于定义出口和入口的约定

            rb.ForTypesDerivedFrom <MEFContract.ICalShow>().Export <MEFContract.ICalShow>();   //指定出口约定  给所有实现接口的类型应用[Export(Type)]特性
            rb.ForType <MEFClient.MyCal>().ImportProperty <MEFContract.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);
        }
Esempio n. 9
0
        /// <summary>
        /// Retrieve registrations for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>Registrations providing the service.</returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor(
            Service service,
            Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException(nameof(registrationAccessor));
            }

            var ts = service as TypedService;

            if (ts == null ||
                ts.ServiceType == typeof(string) ||
                !ts.ServiceType.GetTypeInfo().IsClass ||
                ts.ServiceType.GetTypeInfo().IsSubclassOf(typeof(Delegate)) ||
                ts.ServiceType.GetTypeInfo().IsAbstract ||

                !_predicate(ts.ServiceType) ||
                registrationAccessor(service).Any())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var builder = RegistrationBuilder.ForType(ts.ServiceType);

            RegistrationConfiguration?.Invoke(builder);
            return(new[] { builder.CreateRegistration() });
        }
Esempio n. 10
0
        public TService Provide <TService, TImplementation>(params Parameter[] parameters)
        {
            this.Container.ComponentRegistry.Register(
                RegistrationBuilder.ForType <TImplementation>().As <TService>().InstancePerLifetimeScope().CreateRegistration());

            return(this.Container.Resolve <TService>(parameters));
        }
Esempio n. 11
0
 public IList<AssemblyCatalog> Register(RegistrationBuilder builder)
 {
     builder.ForType<MockDataSource>()
         .Export<IDataSource>()
         .SetCreationPolicy(CreationPolicy.Shared);
     return new List<AssemblyCatalog>() { new AssemblyCatalog(GetType().Assembly, builder) };
 }
Esempio n. 12
0
        /// <summary>
        /// Container生成
        /// </summary>
        /// <returns></returns>
        private static CompositionContainer GetContainer()
        {
            var builder = new RegistrationBuilder();
            builder.ForType(typeof(ManualTest)).Export();
            builder.ForType(typeof(ILogger)).Export();

            var catalog = new AggregateCatalog();
            
            // 現在実行中のアセンブリフォルダからカタログを作成
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder));

            var logProvider = new LogExportProvider();

            // 現在実行中のアセンブリのカタログを元にコンテナを作る
            return new CompositionContainer(catalog, logProvider);
        }
        // Tests for creation policy

        private static RegistrationBuilder ConfigureCreationPolicyConvention <T>()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <T>().SetCreationPolicy(CreationPolicy.NonShared);
            return(convention);
        }
        private static RegistrationBuilder ConfigureExportInterfacesConvention <T>()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <T>().ExportInterfaces((t) => true);
            return(convention);
        }
        // Tests for part metadata

        private static RegistrationBuilder ConfigurePartMetadataConvention <T>()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <T>().AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN);
            return(convention);
        }
Esempio n. 16
0
        public void WhenAccessorNotPropertyAccessExpression_ArgumentExceptionThrown()
        {
            var builder = RegistrationBuilder.ForType <object>();

            Assert.Throws <ArgumentException>(() =>
                                              builder.WithMetadata <TestMetadata>(ep => ep.For(p => 42, 42)));
        }
Esempio n. 17
0
        public void AsEmptyList_CreatesRegistrationWithNoServices()
        {
            var registration = RegistrationBuilder.ForType <object>()
                               .As(new Service[0])
                               .CreateRegistration();

            Assert.Empty(registration.Services);
        }
Esempio n. 18
0
        /// <summary>
        /// Container生成
        /// </summary>
        /// <returns></returns>
        private static CompositionContainer GetContainer()
        {
            var builder = new RegistrationBuilder();

            builder.ForType(typeof(ManualTest)).Export();
            builder.ForType(typeof(ILogger)).Export();

            var catalog = new AggregateCatalog();

            // 現在実行中のアセンブリフォルダからカタログを作成
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder));

            var logProvider = new LogExportProvider();

            // 現在実行中のアセンブリのカタログを元にコンテナを作る
            return(new CompositionContainer(catalog, logProvider));
        }
Esempio n. 19
0
        public void LongestConstructorShortestWithAttribute_ShouldSucceed()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForType<LongestConstructorShortestWithAttribute>().Export();
            ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg");
            ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg");

            var catalog = new TypeCatalog(new[] {
                typeof(LongestConstructorShortestWithAttribute),
                typeof(ConstructorArgs) }, ctx);
            Assert.Equal(2, catalog.Parts.Count());
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            LongestConstructorShortestWithAttribute item = container.GetExportedValue<LongestConstructorShortestWithAttribute>();
            Assert.Equal(10, item.IntArg);
            Assert.Null(item.StringArg);
        }
        public void CreatePart_ImportHasNewScope_NewscopeOnStandardImportShouldThrowComposablePartException()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForType <ContractImpl>().Export <IContract>();
            ctx.ForType <MyEmptyClass>().Export <MyEmptyClass>();
            ctx.ForType <MyEmptyClass>().ImportProperty((import) => import.MyProperty, (c) => c.RequiredCreationPolicy(CreationPolicy.NewScope));
            var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes(typeof(MyEmptyClass), typeof(ContractImpl)), ctx);

            ExceptionAssert.Throws <ComposablePartException>(() =>
            {
                foreach (var p in catalog.Parts)
                {
                    var md = p.ImportDefinitions.Count();
                }
            });
        }
 public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesMatching(t => t.Name.EndsWith("Service") &&
                                    t.Namespace.StartsWith(typeof(FrameworkDependencyRegistrar).Namespace))
     .SetCreationPolicy(CreationPolicy.Shared)
     .ExportInterfaces()
     .Export();
     registrations.ForType <Import>()
     .AddMetadata("ApplicationScoped", true)
     .SetCreationPolicy(CreationPolicy.NonShared)
     .Export();
     registrations.ForType <AppSettings>()
     .AddMetadata("ApplicationScoped", true)
     .SetCreationPolicy(CreationPolicy.NonShared)
     .ExportInterfaces()
     .Export();
 }
Esempio n. 22
0
 static void SetupRegistrationBuilder(RegistrationBuilder rb)
 {
     rb.ForType <SixMapper>()
     .Export <IMapper>();
     SetupUI(rb);
     SetupDAL(rb);
     SetupCore(rb);
 }
        // This set of tests is for imports at the property level
        private static RegistrationBuilder ConfigureImportPropertyConvention <TPart>(Expression <Func <TPart, object> > property)
        {
            var convention = new RegistrationBuilder();

            convention.ForType <TPart>()
            .ImportProperty(property, ib => ib.AsMany(false).AsContractName(ContractNames.ContractX).AsContractType <AB>());

            return(convention);
        }
        public void OfTypeOnePart_ShouldFindOnePart()
        {
            var ctx = new RegistrationBuilder();

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

            Assert.True(catalog.Parts.Count() == 1);
        }
        // Tests follow for constructor parameters

        private static RegistrationBuilder ConfigureImportConstructorParameterConvention <TPart>()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <TPart>()
            .SelectConstructor(cis => cis.Single(), (ci, ib) => ib.AsMany(false).AsContractName(ContractNames.ContractX).AsContractType <IContractA>());

            return(convention);
        }
        public void OfTypeInterfaceWithExport_ShouldFindZeroParts()
        {
            var ctx = new RegistrationBuilder();

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

            Assert.True(catalog.Parts.Count() == 0);
        }
Esempio n. 27
0
        public override void RegisterTransient(Type serviceType, Type implementationType)
        {
            var builder = new RegistrationBuilder();
            builder.ForType(implementationType)
                   .Export(c => c.AsContractType(serviceType))
                   .SetCreationPolicy(CreationPolicy.NonShared);

            this.catalog.Catalogs.Add(new TypeCatalog(new[] { implementationType }, builder));
        }
        public void AmbiguousConstructor_ShouldFail()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForType <AmbiguousConstructors>().Export();
            ctx.ForType <ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg");
            ctx.ForType <ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg");

            var catalog = new TypeCatalog(new[] {
                typeof(AmbiguousConstructors),
                typeof(ConstructorArgs)
            }, ctx);

            Assert.Equal(2, catalog.Parts.Count());
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);

            Assert.Throws <CompositionException>(() => container.GetExportedValue <AmbiguousConstructors>());
        }
Esempio n. 29
0
        public void AmbiguousConstructorWithAttributeAppliedToOne_ShouldSucceed()
        {
            var ctx = new RegistrationBuilder();

            ctx.ForType<AmbiguousConstructorsWithAttribute>().Export();
            ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg");
            ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg");

            var catalog = new TypeCatalog(new[] {
                typeof(AmbiguousConstructorsWithAttribute),
                typeof(ConstructorArgs) }, ctx);
            Assert.Equal(2, catalog.Parts.Count());
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            AmbiguousConstructorsWithAttribute item = container.GetExportedValue<AmbiguousConstructorsWithAttribute>();

            Assert.Equal(10, item.IntArg);
            Assert.Equal("Hello, World", item.StringArg);
        }
Esempio n. 30
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();
        }
Esempio n. 31
0
        public override void RegisterSingleton(Type serviceType, Type implementationType)
        {
            var builder = new RegistrationBuilder();

            builder.ForType(implementationType)
            .Export(c => c.AsContractType(serviceType))
            .SetCreationPolicy(CreationPolicy.Shared);

            this.catalog.Catalogs.Add(new TypeCatalog(new[] { implementationType }, builder));
        }
        /// <summary>
        ///    Retrieves registrations for an unregistered service, to be used
        ///    by the container. If <paramref name="service" /> is a creatable type, a new registration
        ///    will be created; otherwise, an empty enumerable is returned.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
        /// <returns>
        ///    Registrations providing the service.
        /// </returns>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var ts = service as TypedService;

            if (ts == null || ts.ServiceType.IsAbstract || !ts.ServiceType.IsClass)
            {
                yield break;
            }
            yield return(RegistrationBuilder.ForType(ts.ServiceType).CreateRegistration());
        }
        // This set of tests is for exports at the property level

        private static RegistrationBuilder ConfigureExportPropertyConvention <TPart>(Expression <Func <TPart, object> > property)
        {
            var convention = new RegistrationBuilder();

            convention.ForType <TPart>()
            .ExportProperty(property, eb => eb.AsContractType <IContractA>()
                            .AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN));

            return(convention);
        }
        public void AnyConvention_NotDiscoverablePart_ConventionApplied()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <NotDiscoverablePart>().Export();
            AssertHasAttributesUnderConvention <NotDiscoverablePart>(convention, new object[] {
                new PartNotDiscoverableAttribute(),
                new ExportAttribute()
            });
        }
Esempio n. 35
0
 public void Register <TService, TImplementation>()
     where TService : class
     where TImplementation : class, TService
 {
     Container
     .ComponentRegistry
     .Register(RegistrationBuilder.ForType <TImplementation>().As <TService>()
               .InstancePerLifetimeScope()
               .CreateRegistration());
 }
        // This set of tests is for exports at the class declaration level

        private static RegistrationBuilder ConfigureExportInterfaceConvention <TPart>()
        {
            var convention = new RegistrationBuilder();

            convention.ForType <TPart>()
            .Export(eb => eb.AsContractType <IContractA>()
                    .AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN));

            return(convention);
        }
Esempio n. 37
0
        public static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("File Watch Directory must be specifed");
                Console.WriteLine("usage: engine.exe path");
                return -1;
            }

            try
            {
                // Example of convention-based approach
                var registration = new RegistrationBuilder();
                registration.ForType<Logger>().Export<ILogger>();
                var assemblyCatalog = new AssemblyCatalog(typeof(Logger).Assembly, registration);

                var catalog = new AggregateCatalog(
                    assemblyCatalog,
                    new DirectoryCatalog(@".\addins"));

                using (var container = new CompositionContainer(catalog))
                {
                    var engine = new ProcessorEngine(new DirectoryInfo(args[0]));

                    // Bind exports to imports
                    container.ComposeParts(engine);

                    var exports = container.GetExports<IFileProcessor, IFileProcessorMetadata>().ToList();

                    Console.WriteLine("{0} File Processor(s) available", exports.Count);

                    if (exports.Count > 0)
                    {
                        foreach (var export in exports)
                        {
                            Console.WriteLine("{0} file type supported", export.Metadata.SupportedExtension);
                        }
                        engine.ProcessFiles();
                    }
                    else
                    {
                        Console.WriteLine("Add File Processors to the Add-in directory");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
                return -1;
            }
            Console.ReadLine();
            return 0;
        }
Esempio n. 38
0
        public static void Configure()
        {
            var registration = new RegistrationBuilder();

            registration.ForType<IDEAuthQueryContext>()
                        .Export(eb => eb.AsContractName("AuthQueryContext"));

            using (var catalog = new AssemblyCatalog(typeof(IoCStartup).Assembly, registration))
            {
                var container = new CompositionContainer(catalog);

            }
        }
Esempio n. 39
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RegistrationBuilder builder = new RegistrationBuilder();
            builder.ForType<MainWindowViewModel>()
                .Export()
                .ImportProperties<LoadCommand>(info => info.Name == "LoadCommand")
                .ImportProperties<SaveCommand>(info => info.Name == "SaveCommand");

            builder.ForType<LoadCommand>()
                .Export()
                .ImportProperties<MainWindowViewModel>(info => info.Name == "MainWindowViewModel");

            builder.ForType<SaveCommand>()
                .Export()
                .ImportProperties<MainWindowViewModel>(info => info.Name == "MainWindowViewModel");

            builder.ForType<OpenFileDialogService>().Export<IOpenFileDialogService>();
            builder.ForType<StorageManager>().Export<IStorageManager>();

            AssemblyCatalog cat = new AssemblyCatalog(typeof(App).Assembly, builder);
            container = new CompositionContainer(cat);

            base.OnStartup(e);
        }
Esempio n. 40
0
        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>
 /// 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();
 }
Esempio n. 42
0
        static void Main()
        {
            try {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                RegistrationBuilder builder = new RegistrationBuilder();
                builder.ForType<AlarmClockViewPresenter>().Export<AlarmClockViewPresenter>();
                builder.ForType<AlarmViewPresenter>().Export<IAlarmViewPresenter>();
                builder.ForType<ClockViewPresenter>().Export<IClockViewPresenter>();
                builder.ForTypesDerivedFrom<IAlarmClockView>().Export<IAlarmClockView>();
                builder.ForTypesDerivedFrom<IAlarmView>().Export<IAlarmView>();
                builder.ForTypesDerivedFrom<IClockView>().Export<IClockView>();
                //was the default singletons
                var initialAlarmClockTime = DateTime.Now;
                var initialAlarmClockTimeContractName = "InitialClockTime";

                builder.ForType<InitializedAlarmClock>().SelectConstructor(ctors => ctors.First(), (p, ib) =>
                {
                    ib.AsContractName(initialAlarmClockTimeContractName);
                });
                builder.ForType<InitializedAlarmClock>().Export<IAlarmClock>();
                var loc = Assembly.GetExecutingAssembly().Location;
                AssemblyCatalog defaultOrReplacement = null;
                DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(loc));
                var isDebug = false;
#if DEBUG
                isDebug = true;
#endif
                defaultOrReplacement = new AssemblyCatalog(typeof(DefaultViews.DefaultClockView).Assembly, builder);
                if (!isDebug)
                {
                    foreach (var f in dir.GetFiles())
                    {
                        bool match = f.Name == "ReplacementParts.dll";
                        if (match)
                        {
                            defaultOrReplacement = new AssemblyCatalog(f.FullName, builder);
                            break;
                        }
                    }

                }


                var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                //DirectoryCatalog dirCatalog = new DirectoryCatalog(directory,builder);

                AssemblyCatalog exeCatalog = new AssemblyCatalog(typeof(DefaultAlarmClockView).Assembly, builder);


                AggregateCatalog aggCatalog = new AggregateCatalog(exeCatalog, defaultOrReplacement);
                CompositionContainer container = new CompositionContainer(aggCatalog);
                container.ComposeExportedValue<DateTime>(initialAlarmClockTimeContractName, initialAlarmClockTime);


                var alarmClockView = container.GetExportedValue<AlarmClockViewPresenter>().View as Form;
                Application.Run(alarmClockView);
            }catch(Exception exc)
            {
                var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var sw = File.CreateText(dirName+Path.DirectorySeparatorChar + "Houston.txt");
                sw.WriteLine(exc.Message);
                sw.Flush();
                sw.Close();
            }
        }
Esempio n. 43
0
        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>();
        }
Esempio n. 44
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>();
            }
        }
Esempio n. 45
0
 /// <summary>
 /// 添加配置
 /// </summary>
 /// <param name="builder">配置生成器</param>
 protected override void Load( RegistrationBuilder builder ) {
     builder.ForType<Context>().Export<Context>();
     builder.ForType<Operation3>().Export<IOperation3>();
     builder.ForType<Operation4>().Export<IOperation4>();
 }
Esempio n. 46
0
 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);
 }
Esempio n. 47
0
 /// <summary>
 /// 添加配置
 /// </summary>
 /// <param name="builder">配置生成器</param>
 protected override void Load( RegistrationBuilder builder ) {
     builder.ForType<Service>().Export<IService>();
 }
        /// <summary>
        /// Registers the dependencies 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.ForType<Foo>()
                .SetCreationPolicy(CreationPolicy.NonShared)
                .ExportInterfaces()
                .Export();

            var httpRegistrations = new RegistrationBuilder();
            httpRegistrations.ForType<HttpClient>()
                .SelectConstructor(ctor => { return ctor.FirstOrDefault(ci => ci.GetParameters().Length == 0); })
                .SetCreationPolicy(CreationPolicy.NonShared)
                .ExportInterfaces()
                .Export();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(HttpClient).Assembly, httpRegistrations));
        }
Esempio n. 49
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()
                };
            }
        }
Esempio n. 50
0
 /// <summary>
 /// 添加配置
 /// </summary>
 /// <param name="builder">配置生成器</param>
 protected override void Load( RegistrationBuilder builder ) {
     builder.ForType<Operation>().Export<IOperation>();
 }
Esempio n. 51
0
		public IList<AssemblyCatalog> Register(RegistrationBuilder builder)
		{
			builder.ForType<MockPoll>().Export<IPoll>();

			var catalogs = new List<AssemblyCatalog>();

			catalogs.Add(new AssemblyCatalog(typeof(IPoll).Assembly, builder));
			catalogs.Add(new AssemblyCatalog(typeof(MockPoll).Assembly, builder));

			return catalogs;
		}