Example #1
0
        public GrainTypeManager(
            ILocalSiloDetails siloDetails,
            IApplicationPartManager applicationPartManager,
            DefaultPlacementStrategy defaultPlacementStrategy,
            SerializationManager serializationManager,
            MultiClusterRegistrationStrategyManager multiClusterRegistrationStrategyManager,
            ILogger <GrainTypeManager> logger,
            IOptions <GrainClassOptions> grainClassOptions)
        {
            var localTestMode = siloDetails.SiloAddress.Endpoint.Address.Equals(IPAddress.Loopback);

            this.logger = logger;
            this.defaultPlacementStrategy = defaultPlacementStrategy.PlacementStrategy;
            this.serializationManager     = serializationManager;
            this.multiClusterRegistrationStrategyManager = multiClusterRegistrationStrategyManager;
            grainInterfaceMap        = new GrainInterfaceMap(localTestMode, this.defaultPlacementStrategy);
            ClusterGrainInterfaceMap = grainInterfaceMap;
            grainInterfaceMapsBySilo = new Dictionary <SiloAddress, GrainInterfaceMap>();

            var grainClassFeature = applicationPartManager.CreateAndPopulateFeature <GrainClassFeature>();

            this.grainTypes = CreateGrainTypeMap(grainClassFeature, grainClassOptions.Value);

            var grainInterfaceFeature = applicationPartManager.CreateAndPopulateFeature <GrainInterfaceFeature>();

            this.invokers = CreateInvokerMap(grainInterfaceFeature);
            this.InitializeInterfaceMap();
        }
Example #2
0
        static void Configure(IApplicationPartManager apm, IServiceCollection services)
        {
            var assemblies = apm.ApplicationParts
                             .OfType <AssemblyPart>().Select(x => x.Assembly)
                             .ToArray();

            services.AddSingleton(sp => new ClusterActorSystem(assemblies, sp));
            services.AddSingleton(sp => new ClientActorSystem(assemblies, sp));

            services.AddSingleton <IActorSystem>(sp => sp.GetService <ClusterActorSystem>());
            services.AddSingleton <IClientActorSystem>(sp => sp.GetService <ClientActorSystem>());

            services.TryAddSingleton <IDispatcherRegistry>(x => BuildDispatcherRegistry(x, assemblies));
            services.TryAddSingleton <Func <MethodInfo, InvokeMethodRequest, IGrain, string> >(DashboardIntegration.Format);

            services.TryAddSingleton <IActorMiddleware>(DefaultActorMiddleware.Instance);
            services.TryAddSingleton <IActorRefMiddleware>(DefaultActorRefMiddleware.Instance);
            services.TryAddSingleton <IStreamRefMiddleware>(DefaultStreamRefMiddleware.Instance);

            services.TryAdd(new ServiceDescriptor(typeof(IGrainActivator), sp => new DefaultGrainActivator(sp), ServiceLifetime.Singleton));
            services.Decorate <IGrainActivator>(inner => new ActorGrainActivator(inner));

            services.AddTransient <IConfigurationValidator, DispatcherOptionsValidator>();
            services.AddOptions <DispatcherOptions>();
        }
Example #3
0
 public SiloIndexManager(IServiceProvider sp, IGrainFactory gf, IApplicationPartManager apm, ILoggerFactory lf, ITypeResolver tr)
     : base(sp, gf, apm, lf, tr)
 {
     this.InjectableCode        = this.ServiceProvider.GetService <IInjectableCode>() ?? new ProductionInjectableCode();
     this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService <IGrainReferenceRuntime>();
     this.GrainServiceFactory   = this.ServiceProvider.GetRequiredService <IGrainServiceFactory>();
 }
        /// <summary>
        /// Adds the provided assembly to the builder.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <param name="assembly">The assembly.</param>
        /// <returns>The builder with the additionally added assembly.</returns>
        public static IApplicationPartManager AddApplicationPart(this IApplicationPartManager manager, Assembly assembly)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

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

            // Always add the provided part, whether or not it contains generated code.
            manager.AddApplicationPart(new AssemblyPart(assembly));

            // Add all referenced application parts.
            foreach (var referencedAsm in GetApplicationPartAssemblies(assembly))
            {
                var part = new AssemblyPart(referencedAsm);
                if (manager.ApplicationParts.Contains(part))
                {
                    continue;
                }

                manager.AddApplicationPart(part);
            }

            return(manager);
        }
        private static ImmutableDictionary <GrainInterfaceType, GrainInterfaceProperties> CreateInterfaceManifest(
            IEnumerable <IGrainInterfacePropertiesProvider> propertyProviders,
            IApplicationPartManager applicationPartManager,
            GrainInterfaceTypeResolver interfgaceTypeResolver)
        {
            var feature = applicationPartManager.CreateAndPopulateFeature <GrainInterfaceFeature>();
            var builder = ImmutableDictionary.CreateBuilder <GrainInterfaceType, GrainInterfaceProperties>();

            foreach (var value in feature.Interfaces)
            {
                var interfaceType = interfgaceTypeResolver.GetGrainInterfaceType(value.InterfaceType);
                var properties    = new Dictionary <string, string>();
                foreach (var provider in propertyProviders)
                {
                    provider.Populate(value.InterfaceType, interfaceType, properties);
                }

                var result = new GrainInterfaceProperties(properties.ToImmutableDictionary());
                if (builder.ContainsKey(interfaceType))
                {
                    throw new InvalidOperationException($"An entry with the key {interfaceType} is already present."
                                                        + $"\nExisting: {builder[interfaceType].ToDetailedString()}\nTrying to add: {result.ToDetailedString()}"
                                                        + "\nConsider using the [GrainInterfaceType(\"name\")] attribute to give these interfaces unique names.");
                }

                builder.Add(interfaceType, result);
            }

            return(builder.ToImmutable());
        }
Example #6
0
        public GrainTypeManager(
            ILocalSiloDetails siloDetails,
            IApplicationPartManager applicationPartManager,
            PlacementStrategy defaultPlacementStrategy,
            SerializationManager serializationManager,
            ILogger <GrainTypeManager> logger,
            IOptions <GrainClassOptions> grainClassOptions)
        {
            this.logger = logger;
            this.defaultPlacementStrategy = defaultPlacementStrategy;
            this.serializationManager     = serializationManager;
            grainInterfaceMap             = new GrainInterfaceMap(this.defaultPlacementStrategy);
            ClusterGrainInterfaceMap      = grainInterfaceMap;
            GrainTypeResolver             = grainInterfaceMap.GetGrainTypeResolver();
            grainInterfaceMapsBySilo      = new Dictionary <SiloAddress, GrainInterfaceMap>();

            var grainClassFeature = applicationPartManager.CreateAndPopulateFeature <GrainClassFeature>();

            this.grainTypes = CreateGrainTypeMap(grainClassFeature, grainClassOptions.Value);

            var grainInterfaceFeature = applicationPartManager.CreateAndPopulateFeature <GrainInterfaceFeature>();

            this.invokers = CreateInvokerMap(grainInterfaceFeature);
            this.InitializeInterfaceMap();
        }
        private static ImmutableDictionary <GrainType, GrainProperties> CreateGrainManifest(
            IEnumerable <IGrainPropertiesProvider> grainMetadataProviders,
            IApplicationPartManager applicationPartManager,
            GrainTypeResolver grainTypeProvider)
        {
            var feature       = applicationPartManager.CreateAndPopulateFeature <GrainClassFeature>();
            var propertiesMap = ImmutableDictionary.CreateBuilder <GrainType, GrainProperties>();

            foreach (var value in feature.Classes)
            {
                var grainClass = value.ClassType;
                var grainType  = grainTypeProvider.GetGrainType(grainClass);
                var properties = new Dictionary <string, string>();
                foreach (var provider in grainMetadataProviders)
                {
                    provider.Populate(grainClass, grainType, properties);
                }

                var result = new GrainProperties(properties.ToImmutableDictionary());
                if (propertiesMap.ContainsKey(grainType))
                {
                    throw new InvalidOperationException($"An entry with the key {grainType} is already present."
                                                        + $"\nExisting: {propertiesMap[grainType].ToDetailedString()}\nTrying to add: {result.ToDetailedString()}"
                                                        + "\nConsider using the [GrainType(\"name\")] attribute to give these classes unique names.");
                }

                propertiesMap.Add(grainType, result);
            }

            return(propertiesMap.ToImmutable());
        }
Example #8
0
        /// <summary>
        /// Creates and populates a feature.
        /// </summary>
        /// <typeparam name="TFeature">The feature.</typeparam>
        /// <param name="applicationPartManager">The application part manager.</param>
        /// <returns>The populated feature.</returns>
        public static TFeature CreateAndPopulateFeature <TFeature>(this IApplicationPartManager applicationPartManager) where TFeature : new()
        {
            var result = new TFeature();

            applicationPartManager.PopulateFeature(result);
            return(result);
        }
Example #9
0
        //static async Task MainAsync(string[] args)
        //{



        //    var builder = new SiloHostBuilder()
        //        .ConfigureLogging(ConfigureLogging);



        //       .Configure<ClusterOptions>(options =>
        //       {
        //           // https://github.com/dotnet/orleans/issues/5696
        //           options.ClusterId = "0.0.1";
        //           options.ServiceId = serviceId;
        //       })
        //       //.


        //        // .UseConfiguration(LoadClusterConfiguration)
        //        .UseServiceProviderFactory(ConfigureServices)



        //    SiloHost = builder.Build();
        //    await StartAsync();
        //    //Console.WriteLine("Press Ctrl+C to terminate...");
        //    //Console.CancelKeyPress += (s, e) => _exitEvent.Set();

        //    //_exitEvent.WaitOne();

        //    //Console.WriteLine("Stopping...");
        //    //await SiloHost.StopAsync();
        //    //await SiloHost.Stopped;
        //    //Console.WriteLine("Stopped.");

        //}

        //private static ClusterConfiguration LoadClusterConfiguration()
        //{

        //    // var conString = Configuration["SqlServerConnextionString"];
        //    var cluster = new ClusterConfiguration();
        //    //cluster.StandardLoad();
        //    cluster.LoadFromFile("OrleansConfiguration.dev.xml");
        //    // cluster.Globals.SerializationProviders.Add(typeof(CslaOrleansSerialiser).GetTypeInfo());

        //    return cluster;


        //    //cluster.Globals.AdoInvariant = "System.Data.SqlClient";
        //    //cluster.Globals.ClusterId = "OrleansTest";

        //    //cluster.Globals.SeedNodes.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11111));
        //    //cluster.Globals.LivenessEnabled = true;
        //    //cluster.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.SqlServer;

        //    //cluster.Defaults.ProxyGatewayEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30000);
        //    //cluster.Defaults.HostNameOrIPAddress = "localhost";
        //    //cluster.Defaults.Port = 11111;

        //    //  cluster.Globals.DataConnectionStringForReminders = conString;
        //    //  cluster.Globals.AdoInvariantForReminders = "System.Data.SqlClient";

        //    //   cluster.AddAdoNetStorageProvider("AdoNetStorage", connectionString: conString, serializationFormat: AdoNetSerializationFormat.Json);
        //    //  cluster.AddAzureTableStorageProvider("AzureStore", "UseDevelopmentStorage=true");
        //}

        //private static async Task StartAsync()
        //{
        //    //  Serializers.RegisterAll(_siloHost.Services);
        //    await SiloHost.StartAsync();
        //}

        private static void ConfigureApplicationParts(IApplicationPartManager partManger)
        {
            partManger.AddApplicationPart(typeof(IOrleansGrainDataPortalServer).Assembly);
            partManger.AddApplicationPart(typeof(Program).Assembly);
            partManger.AddApplicationPart(typeof(Root).Assembly);
            partManger.AddApplicationPart(typeof(Csla.ApplicationContext).Assembly);
        }
Example #10
0
 public static void AddClientApplicationParts(IApplicationPartManager parts)
 {
     // Add the base classes as well since they use IGrain
     parts.AddApplicationPart(typeof(ISpatialGrain).Assembly);
     // Add own grain interfaces
     parts.AddApplicationPart(typeof(IGridPartitionGrain).Assembly);
     parts.AddApplicationPart(typeof(IGridConfigurationGrain).Assembly);
 }
 public IndexManager(IServiceProvider sp, IGrainFactory gf, IApplicationPartManager apm, ILoggerFactory lf, ITypeResolver typeResolver)
 {
     this.ServiceProvider        = sp;
     this.GrainFactory           = gf;
     this.ApplicationPartManager = apm;
     this.LoggerFactory          = lf;
     this.CachedTypeResolver     = typeResolver;
 }
Example #12
0
        /// <summary>
        /// Adds all assemblies referencing Orleans found in the provided assembly's <see cref="DependencyContext"/>.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <param name="assembly">Assembly to start looking for application parts from.</param>
        /// <returns>The builder with the additionally included assemblies.</returns>
        public static IApplicationPartManagerWithAssemblies AddFromDependencyContext(this IApplicationPartManager manager, Assembly assembly = null)
        {
            assembly ??= Assembly.GetEntryAssembly();
            DependencyContext dependencyContext;

            if (assembly is null || assembly.IsDynamic)
            {
                dependencyContext = DependencyContext.Default;
            }
Example #13
0
 private static void ConfigOtherFolderGrainLoad(IApplicationPartManager applicationPartManager, IEnumerable <string> pathsList, Func <string, string> pathResolveFunc)
 {
     foreach (var path in pathsList)
     {
         var dllFileInfo = new FileInfo(pathResolveFunc(path));
         var assembly    = Assembly.LoadFile(dllFileInfo.FullName);
         applicationPartManager.AddDynamicPart(assembly);
     }
 }
        public IndexManager(IServiceProvider sp, IGrainFactory gf, IApplicationPartManager apm, ILoggerFactory lf, ITypeResolver typeResolver)
        {
            this.ServiceProvider        = sp;
            this.GrainFactory           = gf;
            this.ApplicationPartManager = apm;
            this.LoggerFactory          = lf;
            this.CachedTypeResolver     = typeResolver;

            this.IndexingOptions = this.ServiceProvider.GetOptionsByName <IndexingOptions>(IndexingConstants.INDEXING_OPTIONS_NAME);
        }
Example #15
0
        public TypeMetadataCache(IApplicationPartManager applicationPartManager)
        {
            var grainInterfaceFeature = applicationPartManager.CreateAndPopulateFeature <GrainInterfaceFeature>();

            foreach (var grain in grainInterfaceFeature.Interfaces)
            {
                this.grainToInvokerMapping[grain.InterfaceType]   = grain.InvokerType;
                this.grainToReferenceMapping[grain.InterfaceType] = grain.ReferenceType;
            }
        }
Example #16
0
        private static void AddDefaultApplicationParts(IApplicationPartManager applicationPartsManager)
        {
            var hasApplicationParts = applicationPartsManager.ApplicationParts.OfType <AssemblyPart>()
                                      .Any(part => !part.IsFrameworkAssembly);

            if (!hasApplicationParts)
            {
                applicationPartsManager.AddFromAppDomain();
                applicationPartsManager.AddFromApplicationBaseDirectory();
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class.
        /// </summary>
        /// <param name="partManager"></param>
        /// <param name="loggerFactory">The logger factory.</param>
        public RoslynCodeGenerator(IApplicationPartManager partManager, ILoggerFactory loggerFactory)
        {
            var serializerFeature     = partManager.CreateAndPopulateFeature <SerializerFeature>();
            var grainClassFeature     = partManager.CreateAndPopulateFeature <GrainClassFeature>();
            var grainInterfaceFeature = partManager.CreateAndPopulateFeature <GrainInterfaceFeature>();

            this.knownTypes        = GetKnownTypes();
            this.serializableTypes = new SerializerGenerationManager(GetExistingSerializers(), loggerFactory);
            this.logger            = loggerFactory.CreateLogger <RoslynCodeGenerator>();

            var knownInterfaces = grainInterfaceFeature.Interfaces.Select(i => i.InterfaceType);
            var knownClasses    = grainClassFeature.Classes.Select(c => c.ClassType);

            this.knownGrainTypes = new HashSet <Type>(knownInterfaces.Concat(knownClasses));

            HashSet <string> GetKnownTypes()
            {
                var result = new HashSet <string>();

                foreach (var kt in serializerFeature.KnownTypes)
                {
                    result.Add(kt.Type);
                }
                foreach (var serializer in serializerFeature.SerializerTypes)
                {
                    result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
                    result.Add(RuntimeTypeNameFormatter.Format(serializer.Serializer));
                }

                foreach (var serializer in serializerFeature.SerializerDelegates)
                {
                    result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
                }

                return(result);
            }

            HashSet <Type> GetExistingSerializers()
            {
                var result = new HashSet <Type>();

                foreach (var serializer in serializerFeature.SerializerDelegates)
                {
                    result.Add(serializer.Target);
                }

                foreach (var serializer in serializerFeature.SerializerTypes)
                {
                    result.Add(serializer.Target);
                }

                return(result);
            }
        }
        public ClientManifestProvider(
            IEnumerable <IGrainPropertiesProvider> grainPropertiesProviders,
            IEnumerable <IGrainInterfacePropertiesProvider> grainInterfacePropertiesProviders,
            IApplicationPartManager applicationPartManager,
            GrainTypeResolver grainTypeResolver,
            GrainInterfaceTypeResolver interfaceTypeResolver)
        {
            var grainProperties = CreateGrainManifest(grainPropertiesProviders, applicationPartManager, grainTypeResolver);
            var interfaces      = CreateInterfaceManifest(grainInterfacePropertiesProviders, applicationPartManager, interfaceTypeResolver);

            this.ClientManifest = new GrainManifest(grainProperties, interfaces);
        }
Example #19
0
        public SiloManifestProvider(
            IEnumerable <IGrainPropertiesProvider> grainPropertiesProviders,
            IEnumerable <IGrainInterfacePropertiesProvider> grainInterfacePropertiesProviders,
            IApplicationPartManager applicationPartManager,
            GrainTypeResolver typeProvider,
            GrainInterfaceIdResolver interfaceIdProvider)
        {
            var grains     = CreateGrainManifest(grainPropertiesProviders, applicationPartManager, typeProvider);
            var interfaces = CreateInterfaceManifest(grainInterfacePropertiesProviders, applicationPartManager, interfaceIdProvider);

            this.SiloManifest = new SiloManifest(grains, interfaces);
        }
Example #20
0
        /// <summary>
        /// 装配Actor插件
        /// </summary>
        /// <param name="manager">IApplicationPartManager</param>
        /// <param name="filter">装配的Actor插件所在程序集统一采用"*.Plugin.dll"作为文件名后缀</param>
        public static void AddPluginPart(this IApplicationPartManager manager, string filter = "*.Plugin.dll")
        {
            if (String.IsNullOrEmpty(filter))
            {
                throw new ArgumentNullException(nameof(filter));
            }

            foreach (string fileName in Directory.GetFiles(AppRun.BaseDirectory, filter))
            {
                manager.AddApplicationPart(Assembly.LoadFrom(fileName)).WithReferences().WithCodeGeneration();
            }
        }
Example #21
0
 public ApplicationPartManagerWithAssemblies(IApplicationPartManager manager, IEnumerable <Assembly> additionalAssemblies)
 {
     if (manager is ApplicationPartManagerWithAssemblies builderWithAssemblies)
     {
         this.manager    = builderWithAssemblies.manager;
         this.Assemblies = builderWithAssemblies.Assemblies.Concat(additionalAssemblies).Distinct().ToList();
     }
     else
     {
         this.manager    = manager;
         this.Assemblies = additionalAssemblies;
     }
 }
Example #22
0
        /// <summary>
        /// Adds the provided assembly to the builder.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <param name="assembly">The assembly.</param>
        /// <returns>The builder with the additionally added assembly.</returns>
        public static IApplicationPartManagerWithAssemblies AddApplicationPart(this IApplicationPartManager manager, Assembly assembly)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

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

            return(new ApplicationPartManagerWithAssemblies(manager.AddApplicationPart(new AssemblyPart(assembly)), new[] { assembly }));
        }
Example #23
0
        /// <summary>
        /// Adds default application parts if no non-framework parts have been added.
        /// </summary>
        /// <param name="applicationPartManager">The application part manager.</param>
        /// <returns>The application part manager.</returns>
        public static IApplicationPartManager ConfigureDefaults(this IApplicationPartManager applicationPartsManager)
        {
            var hasApplicationParts = applicationPartsManager.ApplicationParts.OfType <AssemblyPart>()
                                      .Any(part => !part.IsFrameworkAssembly);

            if (!hasApplicationParts)
            {
                applicationPartsManager.AddFromDependencyContext();
                applicationPartsManager.AddFromAppDomain();
                applicationPartsManager.AddFromApplicationBaseDirectory();
            }

            return(applicationPartsManager);
        }
Example #24
0
        private static IApplicationPartManagerWithAssemblies AddParts(IApplicationPartManager parts, SiloSettings siloSettings)
        {
            var results = parts.AddMongoGrains()
                          .AddApplicationPart(typeof(DataChunk).Assembly)
                          .WithCodeGeneration();

            var linkedAsms = GetLinkedAssemblies(siloSettings);

            foreach (var asm in linkedAsms)
            {
                results.AddApplicationPart(asm);
            }

            return(results);
        }
        public SiloManifestProvider(
            IEnumerable <IGrainPropertiesProvider> grainPropertiesProviders,
            IEnumerable <IGrainInterfacePropertiesProvider> grainInterfacePropertiesProviders,
            IOptions <GrainClassOptions> grainClassOptions,
            IApplicationPartManager applicationPartManager,
            GrainTypeResolver typeProvider,
            GrainInterfaceTypeResolver interfaceIdProvider,
            TypeConverter typeConverter)
        {
            var(grainProperties, grainTypes) = CreateGrainManifest(grainClassOptions.Value, grainPropertiesProviders, applicationPartManager, typeProvider);
            var interfaces = CreateInterfaceManifest(grainInterfacePropertiesProviders, applicationPartManager, interfaceIdProvider);

            this.SiloManifest = new GrainManifest(grainProperties, interfaces);
            this.GrainTypeMap = new GrainClassMap(typeConverter, grainTypes);
        }
Example #26
0
        /// <summary>
        /// Adds assemblies from the current <see cref="AppDomain"/> to the builder.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <returns>The builder with the added assemblies.</returns>
        public static IApplicationPartManagerWithAssemblies AddFromAppDomain(this IApplicationPartManager manager)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

            var processedAssemblies = new HashSet <Assembly>(AppDomain.CurrentDomain.GetAssemblies());

            foreach (var assembly in processedAssemblies)
            {
                manager.AddApplicationPart(new AssemblyPart(assembly));
            }

            return(new ApplicationPartManagerWithAssemblies(manager, processedAssemblies));
        }
Example #27
0
        internal void Configure(IApplicationPartManager apm, IServiceCollection services)
        {
            var assemblies = apm.ApplicationParts
                             .OfType <AssemblyPart>().Select(x => x.Assembly)
                             .Distinct()
                             .ToArray();

            var actors = assemblies.SelectMany(x => x.GetTypes())
                         .Where(x => typeof(Actor).IsAssignableFrom(x) && x.IsClass && !x.IsAbstract)
                         .ToArray();

            RegisterStreamSubscriptions(services, actors);
            RegisterSimpleMessageStreamProviders(services);
            RegisterBehaviors(actors);

            BootStreamSubscriptions(services);
        }
        /// <summary>
        /// Adds the provided assembly to the builder as a framework assembly.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <param name="assembly">The assembly.</param>
        /// <returns>The builder with the additionally added assembly.</returns>
        public static IApplicationPartManager AddFrameworkPart(this IApplicationPartManager manager, Assembly assembly)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

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

            return(manager.AddApplicationPart(new AssemblyPart(assembly)
            {
                IsFrameworkAssembly = true
            }));
        }
Example #29
0
        /// <summary>
        /// Adds default application parts if no non-framework parts have been added.
        /// </summary>
        /// <param name="applicationPartsManager">The application part manager.</param>
        /// <returns>The application part manager.</returns>
        public static IApplicationPartManager ConfigureDefaults(this IApplicationPartManager applicationPartsManager)
        {
            var hasApplicationParts = applicationPartsManager.ApplicationParts.OfType <AssemblyPart>()
                                      .Any(part => !part.IsFrameworkAssembly);

            if (!hasApplicationParts)
            {
                applicationPartsManager.AddFromDependencyContext();
#if NETCOREAPP
                applicationPartsManager.AddFromAssemblyLoadContext();
#else
                applicationPartsManager.AddFromAppDomainWithReferences();
#endif
            }

            return(applicationPartsManager);
        }
        public static IApplicationPartManager AddFromAssemblyLoadContext(this IApplicationPartManager manager, Assembly assembly = null)
        {
            assembly ??= typeof(ApplicationPartManagerExtensions).Assembly;
            var assemblies = new HashSet <Assembly>();
            var context    = AssemblyLoadContext.GetLoadContext(assembly);

            foreach (var asm in context.Assemblies)
            {
                // Skip assemblies which have not had code generation executed against them and already-seen assemblies.
                if (!asm.IsDefined(typeof(ApplicationPartAttribute)) || !assemblies.Add(asm))
                {
                    continue;
                }

                manager.AddApplicationPart(asm);
            }

            return(manager);
        }