public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesMatching(t => t.Name.EndsWith("Service"))
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
 }
        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;
        }
 /// <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 IList<AssemblyCatalog> Register(RegistrationBuilder builder)
 {
     builder.ForType<MockDataSource>()
         .Export<IDataSource>()
         .SetCreationPolicy(CreationPolicy.Shared);
     return new List<AssemblyCatalog>() { new AssemblyCatalog(GetType().Assembly, builder) };
 }
 /// <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;
 }
Example #6
0
        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();

            var registration = new RegistrationBuilder();

            registration.ForTypesMatching(t => t.Name.EndsWith("ViewModel"))
                .SelectConstructor(c => c.OrderBy(m => m.GetParameters().Count()).FirstOrDefault())
                .Export();

            registration.ForTypesMatching(t => t.Name.EndsWith("View"))
                .SelectConstructor(c => c.OrderBy(m => m.GetParameters().Count()).FirstOrDefault())
                .Export();

            registration.ForTypesMatching(t => t.Name.EndsWith("Repository"))
                .SelectConstructor(c => c.OrderBy(m => m.GetParameters().Count()).FirstOrDefault())
                .ExportInterfaces(i => i.IsPublic);

            registration.ForTypesMatching(t => t.Name.EndsWith("Module"))
                .SelectConstructor(c => c.OrderBy(m => m.GetParameters().Count()).FirstOrDefault())
                .ExportInterfaces(i => i.IsPublic);

            AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly, registration));

            registration = new RegistrationBuilder();

            registration.ForTypesMatching(t => true)
                        .ExportInterfaces(i => i.IsPublic);

            AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ChatHubProxy).Assembly, registration));
        }
        public static CompositionContainer GetMefContainer(string binDirPath, CompositionBatch batch = null, RegistrationBuilder builder = null)
        {
            if (builder == null)
                builder = new RegistrationBuilder();

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

            builder.ForTypesDerivedFrom<ApiController>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

            var catalogs = new DirectoryCatalog(binDirPath, builder);

            var container = new CompositionContainer(catalogs, CompositionOptions.DisableSilentRejection |
                                                               CompositionOptions.IsThreadSafe);

            if (batch == null)
                batch = new CompositionBatch();

            // make container availalbe for di
            batch.AddExportedValue(container);

            container.Compose(batch);

            return container;
        }
 private static void ScanAssemblies(
     IEnumerable<Assembly> assemblies,
     RegistrationBuilder rb,
     Action<ICustomizersHolder> customizerMutator)
 {
     ScanTypes(assemblies.SelectMany(a => a.GetLoadableTypes()), rb, customizerMutator);
 }
Example #9
0
 PluginManager()
 {
     watchers = new Dictionary<String, FileSystemWatcher>();
     paths = new ObservableCollection<string>();
     paths.CollectionChanged += pathsChanged;
     var registration = new RegistrationBuilder();
 }
        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);
            }
        }
 public IList<AssemblyCatalog> Register(RegistrationBuilder builder)
 {
     builder
         .ForType<StrawPoll>()
         .Export<IPoll>();
     return new List<AssemblyCatalog>() { new AssemblyCatalog(GetType().Assembly, builder)};
 }
        public static IView CreateView(object viewModel)
        {
            var viewName = viewModel.GetType().Name.Replace("ViewModel", "View");
            IView view = null;
            if (IsTesting)
            {
                view = new TestView();
            }
            else
            {
                // View anhand des Namens ermitteln & exportieren
                var registration = new RegistrationBuilder();
                registration.ForTypesMatching<IView>(item=>item.Name.Equals(viewName))
                    .Export<IView>()
                    .SetCreationPolicy(CreationPolicy.NonShared);

                // View erstellen
                var catalog = new AssemblyCatalog(viewModel.GetType().Assembly, registration);
                var container = new CompositionContainer(catalog);
                view = container.GetExportedValue<IView>();
            }
            if (view != null)
                view.DataContext = viewModel;
            return view;
        }
Example #13
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);
                }
            }
        }
Example #14
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>();
        }
Example #15
0
        public static void ConfigureModuleRegistrationBuilder(RegistrationBuilder builder)
        {
            builder.ForTypesDerivedFrom<IReplCommand>()
                .Export<IReplCommand>();

            builder.ForTypesDerivedFrom<ILineProcessor>()
                .Export<ILineProcessor>();
        }
 /// <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 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));
        }
        /// <summary>
        /// Defines the default WebAPI conventions for composing parts.
        /// </summary>
        /// <returns>ReflectionContext.</returns>
        protected override RegistrationBuilder DefineConventions(RegistrationBuilder conventions = null)
        {
            conventions = base.DefineConventions(conventions);
            conventions.ForTypesDerivedFrom<IHttpController>()
                .SetCreationPolicy(CreationPolicy.NonShared)
                .Export();

            return conventions;
        }
Example #19
0
 public static void ConfigureHostingCatalog(AggregateCatalog catalog)
 {
     var hostingBuilder = new RegistrationBuilder();
     ConfigureHostingRegistrationBuilder(hostingBuilder);
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(IScriptEngine).Assembly, hostingBuilder)); //ScriptCS.Contracts
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(ScriptServices).Assembly, hostingBuilder)); //ScriptCS.Core
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(RoslynScriptEngine).Assembly, hostingBuilder)); //CShell.Engine.Roslyn
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(HostingHelpers).Assembly, hostingBuilder)); //CShell.Hosting
 }
Example #20
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;
        }
        internal static IRegisterTypes RegisterAssemblyTypes(params Assembly[] assemblies)
        {
            if (assemblies == null) throw new ArgumentNullException(nameof(assemblies));

            var rb = new RegistrationBuilder();
            rb.Where(type => !typeof(IEntityCustomizer).IsAssignableFrom(type));

            rb.RegisterCallback(customizerMutator => ScanAssemblies(assemblies, rb, customizerMutator));

            return rb;
        }
        internal static IRegisterCustomizers RegisterCustomizators(params Type[] types)
        {
            if (types == null) throw new ArgumentNullException(nameof(types));

            var rb = new RegistrationBuilder();
            rb.Where(type => typeof(IEntityCustomizer).IsAssignableFrom(type));

            rb.RegisterCallback(customizerMutator => ScanTypesCustomizators(types, rb));

            return rb;
        }
 /// <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();
 }
Example #24
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>
        /// Defines registration conventions for the sample application.
        /// </summary>
        /// <param name="conventions">The conventions.</param>
        /// <returns>ReflectionContext.</returns>
        protected override RegistrationBuilder DefineConventions(RegistrationBuilder conventions = null)
        {
            conventions = base.DefineConventions(conventions);

            DefineMvcConventions(conventions);
            DefineWebApiConventions(conventions);

            conventions.ForTypesMatching(t => t.GetCustomAttributes(typeof(ApplicationSharedAttribute), true).Any())
                .AddMetadata(CompositionProvider.ApplicationShared, true);

            return conventions;
        }
Example #26
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);
                    }
                }
            }
        }
 /// <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;
 }
Example #28
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);

            }
        }
Example #29
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);
        }
        private static void ScanTypes(
            IEnumerable<Type> types,
            RegistrationBuilder rb,
            Action<ICustomizersHolder> customizerMutator)
        {
            foreach (var type in GetTypes(types, rb))
            {
                var customizerHolder = new CustomizersHolder(type);
                if (customizerMutator != null)
                    customizerMutator(customizerHolder);

                Admin.AddCustomizer(customizerHolder);
            }
        }
        RegisterOpenGenericAssemblyTypes(ContainerBuilder builder, params Assembly[] assemblies)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

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

            var rb = new RegistrationBuilder <object, OpenGenericScanningActivatorData, DynamicRegistrationStyle>(
                new TypedService(typeof(object)),
                new OpenGenericScanningActivatorData(),
                new DynamicRegistrationStyle());

            rb.RegistrationData.DeferredCallback = builder.RegisterCallback(cr => ScanAssemblies(assemblies, cr, rb));

            return(rb);
        }
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var typedService = service as TypedService;

            if (typedService == null || !typeof(UiComponent).IsAssignableFrom(typedService.ServiceType))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForType(typedService.ServiceType)
                     .As(service)
                     .InstancePerDependency()
                     .OnActivatedInitialiseUiComponent();

            return(new[] { rb.CreateRegistration() });
        }
Example #33
0
        public void Apply(ApplierContext context)
        {
            if (context.ForwardTo == null)
            {
                var registration = _builder
                                   .RegisterType(context.Implementation)
                                   .As(context.Service)
                                   .ConfigureLifecycle(context.Lifetime, null);
            }
            else
            {
                var registration = RegistrationBuilder.ForDelegate(context.Service, (c, parameters) =>
                {
                    return(c.Resolve(context.ForwardTo));
                })
                                   .ConfigureLifecycle(context.Lifetime, null)
                                   .CreateRegistration();

                _builder.RegisterComponent(registration);
            }
        }
        public static IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> Except <T>(this IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> registration, Action <IRegistrationBuilder <T, ConcreteReflectionActivatorData, SingleRegistrationStyle> > customisedRegistration)
        {
            var result = registration.Except <T>();

            result.ActivatorData.PostScanningCallbacks.Add(cr =>
            {
                var rb = RegistrationBuilder.ForType <T>();
                customisedRegistration(rb);
                RegistrationBuilder.RegisterSingleComponent(cr, rb);
            });

            return(result);

            //IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> builder = registration.Except<T>();
            //builder.ActivatorData.PostScanningCallbacks.Add(delegate (IComponentRegistry cr) {
            //    IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle> builder = RegistrationBuilder.ForType<T>();
            //    customisedRegistration(builder);
            //    RegistrationBuilder.RegisterSingleComponent<T, ConcreteReflectionActivatorData, SingleRegistrationStyle>(cr, builder);
            //});
            //return builder;
        }
        /// <summary>
        /// Decorate all components implementing service <typeparamref name="TService"/>
        /// with decorator service <typeparamref name="TDecorator"/>.
        /// </summary>
        /// <typeparam name="TDecorator">Service type of the decorator. Must accept a parameter
        /// of type <typeparamref name="TService"/>, which will be set to the instance being decorated.</typeparam>
        /// <typeparam name="TService">Service type being decorated.</typeparam>
        /// <param name="builder">Container builder.</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 <[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TDecorator, TService>(this ContainerBuilder builder, Func <IDecoratorContext, bool>?condition = null)
            where TDecorator : notnull, TService
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var decoratorService = new DecoratorService(typeof(TService), condition);

            var rb = RegistrationBuilder.ForType <TDecorator>().As(decoratorService);

            var decoratorRegistration = rb.CreateRegistration();

            var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);

            builder.RegisterServiceMiddleware <TService>(middleware, MiddlewareInsertionMode.StartOfPhase);

            // Add the decorator to the registry so the pipeline gets built.
            builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
        }
        Except(
            this IRegistrationBuilder <object, OpenGenericScanningActivatorData, DynamicRegistrationStyle> registration,
            Type openGenericType,
            Action <IRegistrationBuilder <object, ReflectionActivatorData, DynamicRegistrationStyle> > customizedRegistration)
        {
            var result = registration.Except(openGenericType);

            result.ActivatorData.PostScanningCallbacks.Add(cr =>
            {
                var rb = new RegistrationBuilder <object, ReflectionActivatorData, DynamicRegistrationStyle>(
                    new TypedService(openGenericType),
                    new ReflectionActivatorData(openGenericType),
                    new DynamicRegistrationStyle());

                customizedRegistration(rb);

                cr.AddRegistrationSource(new OpenGenericRegistrationSource(rb.RegistrationData, rb.ResolvePipeline, rb.ActivatorData));
            });

            return(result);
        }
        public static void AsExternalService <TLimit, TActivatorData, TRegistrationStyle>(
            this IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> builder)
            where TActivatorData : IConcreteActivatorData
            where TRegistrationStyle : SingleRegistrationStyle
        {
            var registration = RegistrationBuilder.CreateRegistration(builder);
            var serviceType  = (registration.Services.FirstOrDefault() as TypedService)?.ServiceType;

            if (serviceType != null)
            {
                var serviceBinding = new ServiceBindingInfo
                {
                    ServiceType = serviceType,
                    IsExternal  = true
                };

                builder.SingleInstance();
                builder.ExternallyOwned();
                builder.WithMetadata(nameof(ServiceBindingInfo), serviceBinding);
            }
        }
Example #38
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 (service == null)
            {
                throw new ArgumentNullException("service");
            }
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException("registrationAccessor");
            }

            var ts = service as IServiceWithType;

            if (ts != null && ts.ServiceType.IsDelegate())
            {
                var resultType        = ts.ServiceType.FunctionReturnType();
                var resultTypeService = ts.ChangeType(resultType);
                var hasArguments      = ts.ServiceType.IsGenericType && ts.ServiceType.GetGenericArguments().Length > 1;

                return(registrationAccessor(resultTypeService)
                       .Where(r => r.Target != null && (hasArguments || r.Target.Sharing == InstanceSharing.None))
                       .Select(r =>
                {
#if WINDOWS_PHONE
                    var factory = new Util.WindowsPhone.Wp7FactoryGenerator(ts.ServiceType, r, ParameterMapping.Adaptive);
#else
                    var factory = new Lazy <FactoryGenerator>(() => new FactoryGenerator(ts.ServiceType, ParameterMapping.Adaptive));
#endif
                    var rb = RegistrationBuilder.ForDelegate(ts.ServiceType, (c, p) => factory.Value.GenerateFactory(resultTypeService, r.Target, c, p))
                             .InstancePerLifetimeScope()
                             .ExternallyOwned()
                             .As(service)
                             .Targeting(r);

                    return rb.CreateRegistration();
                }));
            }

            return(Enumerable.Empty <IComponentRegistration>());
        }
Example #39
0
    public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        if (service == null)
        {
            throw new ArgumentNullException("service");
        }
        if (registrationAccessor == null)
        {
            throw new ArgumentNullException("registrationAccessor");
        }
        IServiceWithType ts = service as IServiceWithType;

        if (ts == null || !(ts.ServiceType.IsGenericType && ts.ServiceType.GetGenericTypeDefinition() == typeof(DataContext <>)))
        {
            yield break;
        }
        yield return(RegistrationBuilder.ForType(ts.ServiceType)
                     .AsSelf()
                     .WithParameter(new NamedParameter("databaseName", "test"))
                     .WithParameter(new NamedParameter("serverName", "test2"))
                     .CreateRegistration());
    }
        /// <summary>
        /// Retrieve a registration for an unregistered service, to be used
        /// by the container.
        /// </summary>
        /// <param name="service">The service that was requested.</param>
        /// <param name="registrationAccessor">Not used; required by the interface.</param>
        /// <returns>
        /// Registrations for the service.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="service" /> is <see langword="null" />.
        /// </exception>
        public IEnumerable <IComponentRegistration> RegistrationsFor(
            Service service,
            Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            var typedService = service as TypedService;

            if (typedService == null || !this.CanMockService(typedService))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var rb = RegistrationBuilder.ForDelegate((c, p) => this.CreateMock(c, typedService))
                     .As(service)
                     .InstancePerLifetimeScope();

            return(new[] { rb.CreateRegistration() });
        }
Example #41
0
        CacheInSession <TLimit, TActivatorData, TSingleRegistrationStyle>(
            this IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> registration)
            where TActivatorData : IConcreteActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            var services = registration.RegistrationData.Services.ToArray();

            registration.RegistrationData.ClearServices();

            return(registration
                   .ExternallyOwned()
                   .OnRegistered(e => e.ComponentRegistryBuilder.Register(RegistrationBuilder
                                                                          .ForDelegate((c, p) =>
            {
                var session = HttpContext.Current.Session;
                object result;
                lock (session.SyncRoot)
                {
                    var key = e.ComponentRegistration.Id.ToString();
                    result = session[key];
                    if (result == null)
                    {
                        result = c.ResolveComponent(new ResolveRequest(null, e.ComponentRegistration, p));
                        session[key] = result;
                    }
                }

                return result;
            })
                                                                          .As(services)
                                                                          .InstancePerLifetimeScope()
                                                                          .ExternallyOwned()
                                                                          .CreateRegistration())));
        }
    public IEnumerable <IComponentRegistration> RegistrationsFor(
        Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        IServiceWithType typedService = service as IServiceWithType;

        if (typedService == null)
        {
            yield break;
        }
        if (!(typedService.ServiceType.IsGenericType &&
              typedService.ServiceType.GetGenericTypeDefinition() == typeof(IAdapter <>)))
        {
            yield break;
        }
        Type t = typedService.ServiceType.GetGenericArguments()[0];
        IComponentRegistration registration =
            RegistrationBuilder.ForDelegate((c, p) => c.ResolveNamed(t.Namespace, typedService.ServiceType, p))
            .As(service)
            .CreateRegistration();

        yield return(registration);
    }
    public IEnumerable <IComponentRegistration> RegistrationsFor(Service service,
                                                                 Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
    {
        IServiceWithType typedService = service as IServiceWithType;

        if (typedService == null)
        {
            yield break;
        }
        if (typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IHandleEvent <>))
        {
            IEnumerable <IComponentRegistration> eventRegistrations = registrationAccessor(new TypedService(typeof(IEvent)));
            foreach (IComponentRegistration eventRegistration in eventRegistrations)
            {
                Type handleEventType = typeof(IHandleEvent <>).MakeGenericType(eventRegistration.Activator.LimitType);
                IComponentRegistration handleEventRegistration = RegistrationBuilder.ForDelegate((c, p) => c.Resolve(handleEventType, p))
                                                                 .As(service)
                                                                 .CreateRegistration();
                yield return(handleEventRegistration);
            }
        }
    }
Example #44
0
        public void AddingConcreteImplementationWhenAdapterImplementationsExist_AddsChainedAdapters()
        {
            var registry = new ComponentRegistry();

            registry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
            registry.AddRegistrationSource(new MetaRegistrationSource());
            registry.Register(RegistrationBuilder.ForType <object>().CreateRegistration());

            var chainedService = new TypedService(typeof(Meta <Func <object> >));

            var pre = registry.RegistrationsFor(chainedService);

            Assert.AreEqual(1, pre.Count());

            Func <object> func = () => new object();

            registry.Register(RegistrationBuilder.ForDelegate((c, p) => func).CreateRegistration());

            var post = registry.RegistrationsFor(chainedService);

            Assert.AreEqual(2, post.Count());
        }
Example #45
0
        /// <summary>
        /// Build MEF catalog and create composition container
        /// </summary>
        /// <returns>Configured composition container</returns>
        private CompositionContainer CreateCompositionContainer()
        {
            // In addition to explicitly exported classes, auto-export all web api controllers
            var rb = new RegistrationBuilder();

            rb.ForTypesMatching <ApiController>(t => typeof(ApiController).IsAssignableFrom(t) && t.Name.EndsWith("Controller"))
            .Export()
            .SetCreationPolicy(CreationPolicy.NonShared);
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb);

            // Create composition container
            var container = new CompositionContainer(catalog);

            container.ComposeExportedValue <INameGenerator>(new NameGenerator());
            container.ComposeExportedValue(new BooksDemoDataOptions
            {
                MinimumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MinimumNumberOfBooks"]),
                MaximumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MaximumNumberOfBooks"])
            });

            return(container);
        }
        static void ScanAssemblies(IEnumerable <Assembly> assemblies, IComponentRegistry cr, IRegistrationBuilder <object, ScanningActivatorData, DynamicRegistrationStyle> rb)
        {
            rb.ActivatorData.Filters.Add(t =>
                                         rb.RegistrationData.Services.OfType <IServiceWithType>().All(swt =>
                                                                                                      swt.ServiceType.IsAssignableFrom(t)));

            foreach (var t in assemblies
                     .SelectMany(a => a.GetTypes())
                     .Where(t =>
                            t.IsClass &&
                            !t.IsAbstract &&
                            !t.IsGenericTypeDefinition &&
                            !t.IsDelegate() &&
                            rb.ActivatorData.Filters.All(p => p(t))))
            {
                var scanned = RegistrationBuilder.ForType(t)
                              .FindConstructorsWith(rb.ActivatorData.ConstructorFinder)
                              .UsingConstructor(rb.ActivatorData.ConstructorSelector)
                              .WithParameters(rb.ActivatorData.ConfiguredParameters)
                              .WithProperties(rb.ActivatorData.ConfiguredProperties);

                scanned.RegistrationData.CopyFrom(rb.RegistrationData, false);

                foreach (var action in rb.ActivatorData.ConfigurationActions)
                {
                    action(t, scanned);
                }

                if (scanned.RegistrationData.Services.Any())
                {
                    RegistrationBuilder.RegisterSingleComponent(cr, scanned);
                }
            }

            foreach (var postScanningCallback in rb.ActivatorData.PostScanningCallbacks)
            {
                postScanningCallback(cr);
            }
        }
        /// <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>
        /// <remarks>
        /// If the source is queried for service s, and it returns a component that implements both s and s', then it
        ///             will not be queried again for either s or s'. This means that if the source can return other implementations
        ///             of s', it should return these, plus the transitive closure of other components implementing their
        ///             additional services, along with the implementation of s. It is not an error to return components
        ///             that do not implement <paramref name="service"/>.
        /// </remarks>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var typedService = service as TypedService;

            if (typedService == null)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var instances = base.GetServices(typedService.ServiceType);

            if (instances != null)
            {
                return(instances
                       .Select(i => RegistrationBuilder.ForDelegate(i.GetType(), (c, p) => i).As(typedService.ServiceType)
                               .InstancePerMatchingLifetimeScope(_lifetimeScope.Tag)
                               .PreserveExistingDefaults()
                               .CreateRegistration()));
            }

            return(Enumerable.Empty <IComponentRegistration>());
        }
        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);
        }
Example #49
0
        public void Configuration(IAppBuilder app)
        {
            // Initialize data store
            new DataStoreInitializer().InitializeDataStoreAsync().Wait();

            // Add CORS to be able to call Web API from other hosts
            app.UseCors(CorsOptions.AllowAll);

            // Enable application insights
            app.UseApplicationInsights();

            // Configure JSON formatter
            var settings = GlobalConfiguration.Configuration.Formatters
                           .JsonFormatter
                           .SerializerSettings;

            settings.Formatting       = Formatting.Indented;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Setup dependency injection
            var registrationBuilder = new RegistrationBuilder();

            registrationBuilder.ForType <ProductTable>().Export <IProductTable>().SetCreationPolicy(CreationPolicy.NonShared);
            registrationBuilder.ForType <OrderTable>().Export <IOrderTable>().SetCreationPolicy(CreationPolicy.NonShared);
            registrationBuilder.ForTypesDerivedFrom <ApiController>().Export().SetCreationPolicy(CreationPolicy.NonShared);
            var catalog   = new AssemblyCatalog(Assembly.GetExecutingAssembly(), registrationBuilder);
            var container = new CompositionContainer(catalog, true);

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

            configuration.DependencyResolver = new MefDependencyResolver(container);
            configuration.MapHttpAttributeRoutes();
            configuration.Services.Add(typeof(IExceptionLogger), new ApplicationInsightsExceptionLogger(new TelemetryClient()));
            configuration
            .EnableSwagger(config => config.SingleApiVersion("v1", "Technical Summit Shop API"))
            .EnableSwaggerUi();
            app.UseWebApi(configuration);
        }
Example #50
0
        static IComponentRegistration BuildRegistration <TSettings>() where TSettings : ISettings, new()
        {
            return(RegistrationBuilder
                   .ForDelegate((c, p) =>
            {
                var storecontext = c.Resolve <IStoreContext>();
                string currentStoreId = "";
                if (storecontext != null)
                {
                    currentStoreId = storecontext.CurrentStore != null ? storecontext.CurrentStore.Id : "";
                }
                //uncomment the code below if you want load settings per store only when you have two stores installed.
                //var currentStoreId = c.Resolve<IStoreService>().GetAllStores().Count > 1
                //    c.Resolve<IStoreContext>().CurrentStore.Id : 0;

                //although it's better to connect to your database and execute the following SQL:
                //DELETE FROM [Setting] WHERE [StoreId] > 0
                return c.Resolve <ISettingService>().LoadSetting <TSettings>(currentStoreId);
            })
                   .InstancePerLifetimeScope()
                   .CreateRegistration());
        }
Example #51
0
        RegisterDynamically(
            this ContainerBuilder builder,
            Type typeLimit,
            Func <IComponentContext, object> @delegate)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (@delegate == null)
            {
                throw new ArgumentNullException(nameof(@delegate));
            }

            Func <IComponentContext, IEnumerable <AF.Core.Parameter>, object> @del = (c, p) => @delegate(c);

            var rb = RegistrationBuilder.ForDelegate(typeLimit, @del);

            rb.RegistrationData.DeferredCallback = builder.RegisterCallback(cr => RegistrationBuilder.RegisterSingleComponent(cr, rb));

            return(rb);
        }
        public void MapType_ShouldReturnProjectedAttributesForType()
        {
            var builder = new RegistrationBuilder();

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

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

            var exports = new List <object>();

            exports.AddRange(projectedType1.GetCustomAttributes(typeof(ExportAttribute), false));
            exports.AddRange(projectedType2.GetCustomAttributes(typeof(ExportAttribute), false));
            Assert.Equal(2, exports.Count);

            foreach (var exportAttribute in exports)
            {
                Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType);
                Assert.Null(((ExportAttribute)exportAttribute).ContractName);
            }
        }
Example #53
0
        private static CompositionContainer CreateMEFContainer()
        {
            var registrationBuilder = new RegistrationBuilder();

            registrationBuilder
            .ForTypesDerivedFrom <ITimeseriesSource>()
            .SetCreationPolicy(CreationPolicy.NonShared)
            .ExportInterfaces(x => x.IsPublic);

            var aggregateCatalog = new AggregateCatalog();

            aggregateCatalog.Catalogs.Add(
                new AssemblyCatalog(Assembly.GetExecutingAssembly(), registrationBuilder));

            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(baseDirectory, ModuleSearchPattern, registrationBuilder));

            return(new CompositionContainer(aggregateCatalog,
                                            CompositionOptions.DisableSilentRejection |
                                            CompositionOptions.IsThreadSafe));
        }
Example #54
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service,
                                                                     Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var serviceWithType = service as IServiceWithType;

            if (serviceWithType != null)
            {
                object instance;
                if (_core.TryResolve(serviceWithType.ServiceType, out instance))
                {
                    var data = new RegistrationData(service)
                    {
                        Sharing  = InstanceSharing.Shared,
                        Lifetime = new RootScopeLifetime()
                    };

                    yield return
                        (RegistrationBuilder.CreateRegistration(Guid.NewGuid(), data,
                                                                new ProvidedInstanceActivator(instance), new[] { service }));
                }
            }
        }
        /// <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>
        /// <exception cref="System.ArgumentNullException">service</exception>
        /// <remarks>
        /// If the source is queried for service s, and it returns a component that implements both s and s', then it
        /// will not be queried again for either s or s'. This means that if the source can return other implementations
        /// of s', it should return these, plus the transitive closure of other components implementing their
        /// additional services, along with the implementation of s. It is not an error to return components
        /// that do not implement <paramref name="service" />.
        /// </remarks>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            _log.Info(format => format(Resources.MoqRegistrationSource_RegistrationsFor_InfoFormat, service.Description));

            IComponentRegistration[] existingRegistrations = registrationAccessor(service).ToArray();
            if (existingRegistrations.Length > 0)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var  typedService = service as TypedService;
            bool canMock      = typedService != null && (typedService.ServiceType.IsInterface || typedService.ServiceType.IsAbstract || !typedService.ServiceType.IsSealed);

            if (canMock)
            {
                _log.Debug(format => format(Resources.MoqRegistrationSource_RegistrationsFor_PreMockCreateFormat, service.Description));
                return(new[]
                {
                    RegistrationBuilder
                    .ForDelegate((context, parameters) =>
                    {
                        MethodInfo typedMethod = _createMethod.MakeGenericMethod(new[] { typedService.ServiceType });
                        var mock = (Mock)typedMethod.Invoke(this, null);
                        return mock.Object;
                    })
                    .As(typedService)
                    .SingleInstance()
                    .CreateRegistration()
                });
            }

            return(Enumerable.Empty <IComponentRegistration>());
        }
        /// <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))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            var typeInfo = ts.ServiceType.GetTypeInfo();

            if (!typeInfo.IsClass ||
                typeInfo.IsSubclassOf(typeof(Delegate)) ||
                typeInfo.IsAbstract ||
                typeInfo.IsGenericTypeDefinition ||
                !_predicate(ts.ServiceType) ||
                registrationAccessor(service).Any())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            if (typeInfo.IsGenericType && !ShouldRegisterGenericService(typeInfo))
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

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

            RegistrationConfiguration?.Invoke(builder);
            return(new[] { builder.CreateRegistration() });
        }
Example #57
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);

            if (Directory.Exists(PluginPath))
            {
                foreach (string path in new DirectoryInfo(PluginPath).GetFiles().Select(p => p.FullName).Where(p => p.ToLower().EndsWith(".dll")))
                {
                    var assembly = System.Reflection.Assembly.LoadFile(path);
                    catalog.Catalogs.Add(new AssemblyCatalog(assembly, builder));
                }
            }

            var container = new CompositionContainer(catalog);

            return(container.GetExportedValue <PluginManager>());
        }
        /// <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>
        /// <remarks>
        /// If the source is queried for service s, and it returns a component that implements both s and s', then it
        ///             will not be queried again for either s or s'. This means that if the source can return other implementations
        ///             of s', it should return these, plus the transitive closure of other components implementing their
        ///             additional services, along with the implementation of s. It is not an error to return components
        ///             that do not implement <paramref name="service"/>.
        /// </remarks>
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var serviceWithType = service as IServiceWithType;

            if (serviceWithType == null)
            {
                yield break;
            }

            var serviceType = serviceWithType.ServiceType;

            if (!typeof(PersistentConnection).IsAssignableFrom(serviceType))
            {
                yield break;
            }

            var rb = RegistrationBuilder
                     .ForType(serviceType)
                     .As(typeof(PersistentConnection), serviceType)
                     .InstancePerDependency();

            yield return(rb.CreateRegistration());
        }
Example #59
0
        public IEnumerable <IComponentRegistration> RegistrationsFor(
            Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            var swt = service as IServiceWithType;

            if (swt == null || !swt.ServiceType.IsModelOrEntity())
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            object instance = null;

            try
            {
                instance = new SpecimenContext(GetFixture()).Resolve(swt.ServiceType);
            }
            catch (Exception)
            {
                return(Enumerable.Empty <IComponentRegistration>());
            }

            return(new[] { RegistrationBuilder.ForDelegate(swt.ServiceType, (c, p) => instance).CreateRegistration() });
        }
        public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (registrationAccessor == null)
            {
                throw new ArgumentNullException(nameof(registrationAccessor));
            }

            Type constructedImplementationType;

            Service[] services;
            if (OpenGenericServiceBinder.TryBindServiceType(service, _registrationData.Services, _activatorData.ImplementationType, out constructedImplementationType, out services))
            {
                yield return(RegistrationBuilder.CreateRegistration(
                                 Guid.NewGuid(),
                                 _registrationData,
                                 new ReflectionActivator(constructedImplementationType, _activatorData.ConstructorFinder, _activatorData.ConstructorSelector, _activatorData.ConfiguredParameters, _activatorData.ConfiguredProperties),
                                 services));
            }
        }