working on it ...

Filters

Explore Public Snippets

Sort by

Found 13 snippets matching: assembly.load

    public by p.kontalis  1225  0  6  0

    Replace Assembly.LoadWithPartialName with Assembly.Load

    The Assembly.LoadWithPartialName has been deprecated. From now on you have to use Assembly.Load
    '###Till .NET Framework 2.0 you can Load an assembly by its name
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.LoadWithPartialName("System.Windows.Forms")
    
    '###After .Net Framework 2.0 you have to use Assembly.Load
    '###Therefore you have to give all the assembly information but the public token is not the same per pc
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.Load("System.Windows.Forms, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 7a84f7ac56134e3a")
    
    '###In order to bypass this wall either you retrieve it from the registry or you use the GetType(Form) for the retrieval.
    Dim AssemblyLoadString As String = GetType(Form).AssemblyQualifiedName.ToString.Substring(GetType(Form).AssemblyQualifiedName.ToString.IndexOf(",") + 2)
    Dim FormsAssembly As Reflection.Assembly = Reflection.Assembly.Load(AssemblyLoadString)                        

    public by msdn  423  0  5  0

    TryInitializeWindowsRuntimeTypeWithAssembly: Initialize a type defined in an assembly that is not loaded by default

    Initialize a type defined in an assembly that is not loaded by default Assembly to be loaded to fetch the type name of type to be fetched from the loaded assembly null if type cannot be loaded
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    /// <summary>
    /// Initialize a type defined in an assembly that is not loaded by default
    /// </summary>
    /// <param name="assemblyName">Assembly to be loaded to fetch the type</param>
    /// <param name="assemblyQualifiedTypeName">name of type to be fetched from the loaded assembly</param>
    /// <returns>null if type cannot be loaded</returns>
    protected static Type TryInitializeWindowsRuntimeTypeWithAssembly(string assemblyName, string assemblyQualifiedTypeName)
    {
        try
        {
            Assembly assembly = Assembly.Load(assemblyName);
            return assembly.GetType(assemblyQualifiedTypeName);
        }
        catch (System.IO.IOException)
        {
            return null;
        }
        // if the type can't be loaded or any dependent assembly was not found, return false as this is a legacy platform.
        catch (TypeLoadException)
        {
            return null;
        }
    }

    external by ritalin  41244  0  3  0

    .NET Assembly loader for Powershell. Based on https://gist.github.com/guitarrapc/72bffd1e1c12bec100f9#file-testmodule-psm1

    .NET Assembly loader for Powershell. Based on https://gist.github.com/guitarrapc/72bffd1e1c12bec100f9#file-testmodule-psm1: LoadAssembly.ps1
    function LoadAssembly {
        [CmdletBinding()]
        param (
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            [string[]]$asmNames,
            [string]$baseDir = $PSScriptRoot
        )
        begin {
            $domain = [System.AppDomain]::CurrentDomain
            [Reflection.Assembly[]]$asms = $domain.GetAssemblies()
            $cache = New-Object "System.Collections.Generic.HashSet[string]" (,[string[]]$asms.GetName().Name)
            
            $path = $domain.getType().Assembly.Location
            $searchPath = $baseDir,([IO.FileInfo]$path).Directory.FullName
        }
        process {
            foreach ($asmName in $asmNames) {
                LoadAssemblyInternal $asmName $searchPath $cache
            }
        }
    }
    
    function LoadAssemblyInternal([string[]]$asmNames, [string[]]$searchPath, $cache) {
        foreach ($asmName in $asmNames) {
            if (-not $cache.Contains($asmName)) {
                $path = $searchPath | ls -filter "$asmName.dll" | select -first 1
                if ($path -ne $null) {
                    Write-Verbose "Try Loading: $path"
                    [byte[]]$binary = [System.IO.File]::ReadAllBytes($path.FullName)
                    $asm = [System.Reflection.Assembly]::Load($binary);
                    $asm
                    
                    Write-Verbose "Loaded: $($asm.FullName)"
                    
                    $cache.Add($asm.GetName().Name) | Out-Null
    
                    LoadAssemblyInternal $asm.GetReferencedAssemblies().Name $searchPath $cache
                }
            }
        }
    }
    
    
    

    external by Ikiru Yoshizaki  128  0  2  0

    Assembly.Load() then Import-Module as DynamicModule

    Assembly.Load() then Import-Module as DynamicModule: TestModule.psm1
    # Load Assembly without dll Lock
    function LoadAssembly ([System.Reflection.AssemblyName[]]$Arr, [string]$Directory)
    {
        $loadeAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies();
        $names = New-Object System.Collections.Generic.List[string];
        foreach ($assem in $loadeAssemblies)
        {
            $names.Add($assem.FullName);
        }
    
        foreach ($anam in $Arr)
        {
            if (! ($names.Contains($anam.FullName)))
            {
                try
                {
                    [byte[]]$binary = [System.IO.File]::ReadAllBytes((Join-Path $Directory $anam.Name) + ".dll");
                    $loadeAssembly = [System.Reflection.Assembly]::Load($binary);
                    $referencedAssemblies = $loadeAssemblies.GetReferencedAssemblies();
                    LoadAssembly($referencedAssemblies, $Directory);
                }
                catch
                {
                }
            }
        }
    }
    
    # Load Assembly as byte[] and Import Module as DynamicModule
    function ImportModuleToCurrentAppDomain ([string]$Path)
    {
        [byte[]]$primary = [System.IO.File]::ReadAllBytes($Path);
        $assembly = [System.Reflection.Assembly]::Load($primary);
        $arr = $assembly.GetReferencedAssemblies();
        LoadAssembly -Arr $arr -Directory (Split-Path $Path -Parent);
        return (Import-Module -Assembly $assembly -PassThru);
    }
    
    # Find Module Path
    $moduleName = "TestModule";
    $dllName = "$moduleName.dll";
    $parentPath = [System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path);
    $myDllPath = Join-Path $parentPath $dllName;
    
    if (Test-Path $myDllPath)
    {
        # get from current path. Normally always go this path
        $path = $myDllPath;
    }
    else
    {
        Write-Warning "Search Module"
        # Stop Explorer at first hit
        $moduleRoot = (Get-Module -ListAvailable -Name $moduleName | select -First 1).ModuleBase;
        $path = Join-Path $moduleRoot $dllName;
    }
    
    # Import as DyanmicModule
    $module = ImportModuleToCurrentAppDomain -Path $path
    
    
    

    external by Kirill Osenkov  2  0  1  0

    Why Assembly.LoadFile is not the right API to call

    Why Assembly.LoadFile is not the right API to call: AssemblyLoadFile.md
    Assembly.LoadFile is almost always the wrong API to call inside an application. It says to the CLR “hands off, this assembly will live in its own little universe and don’t you apply any of your normal rules for loading assemblies”.  Below you’ve effectively loaded two of these universes and one doesn’t see the other. LoadFile also forces you to hook onto AssemblyResolve (like you’ve done below[1]) and tell the CLR about every dependency that assembly needs to resolve. It also opts you out of other things such as binding redirects, retargeting (v1 portable won’t load below) and a few other things.
    
    Assembly.LoadFile is used by designers, and should be called Assembly.LoadFile_ForDesignerUseOnly, it’s unfortunate it has such as tempting name.
    
    If this is inside of VS, it is most definitely not the correct API to call. You want to use Assembly.Load, Assembly.LoadFrom and/or use VS related APIs for registering binding paths. It already has an assembly resolve, and no one else should be hooking onto it.
    
    [1] That below code has subtle bug, try do a LoadFrom on Microsoft.VisualStudio.CoreUtility.dll before calling LoadFile – now there’s two versions of it loaded, and you’ll return the wrong one from AssemblyResolve.
    
    
    

    external by Kazark  11  0  1  0

    LINQPad snippet for debugging assembly load problems

    LINQPad snippet for debugging assembly load problems: AssemblyAttributes.cs
    foreach (var assembly in assemblies) {
    	Console.WriteLine("Assembly: {0}", assembly);
    	Console.WriteLine("Framework: {0}", ((System.Runtime.Versioning.TargetFrameworkAttribute)Assembly.LoadFrom(assembly).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute)).First()).FrameworkDisplayName);
    	Console.WriteLine("Runtime: {0}", Assembly.LoadFrom(assembly).ImageRuntimeVersion);
    	Console.WriteLine("Architecture: {0}", AssemblyName.GetAssemblyName(assembly).ProcessorArchitecture);
    	Console.WriteLine();
    }
    
    

    external by Kristian Hellang  471  0  3  0

    Assembly loading and scanning

    Assembly loading and scanning: Program.cs
    public static class Program
    {
        private static readonly AssemblyName CurrentAssemblyName = typeof(Program).Assembly.GetName();
    
        public static void Main()
        {
            var mainDomain = AppDomain.CurrentDomain;
    
            var assemblyFolders = mainDomain.GetAssemblyFolders();
    
            var assemblyNames = GetAssemblyNames(assemblyFolders);
    
            var assembliesToLoad = GetAssembliesToLoad(assemblyNames);
    
            var loadedAssemblies = mainDomain.LoadAssemblies(assembliesToLoad);
    
            Console.WriteLine("Loaded the following assemblies:");
    
            foreach (var loadedAssembly in loadedAssemblies)
            {
                Console.WriteLine(loadedAssembly);
            }
    
            Console.ReadLine();
        }
    
        private static IEnumerable<string> GetAssemblyFolders(this AppDomain appDomain)
        {
            var assemblyFolders = new List<string>();
    
            var setupInfo = appDomain.SetupInformation;
    
            if (!string.IsNullOrEmpty(setupInfo.PrivateBinPath))
            {
                var binPaths = setupInfo.PrivateBinPath.Split(';');
    
                foreach (var binPath in binPaths)
                {
                    if (!string.IsNullOrEmpty(binPath))
                    {
                        assemblyFolders.Add(binPath.Trim());
                    }
                }
            }
    
            if (string.IsNullOrEmpty(setupInfo.PrivateBinPath))
            {
                assemblyFolders.Add(setupInfo.ApplicationBase);
            }
    
            return assemblyFolders.ToArray();
        }
    
        private static IEnumerable<AssemblyName> GetAssemblyNames(IEnumerable<string> assemblyFolders)
        {
            var assemblyNames = new HashSet<AssemblyName>();
    
            foreach (var assemblyFolder in assemblyFolders)
            {
                var assemblyPaths = Directory.EnumerateFiles(assemblyFolder, "*.dll");
    
                foreach (var assemblyPath in assemblyPaths)
                {
                    assemblyNames.Add(AssemblyName.GetAssemblyName(assemblyPath));
                }
            }
    
            return assemblyNames.ToArray();
        }
    
        private static IEnumerable<AssemblyName> GetAssembliesToLoad(IEnumerable<AssemblyName> assemblyNames)
        {
            var assembliesToLoad = new List<AssemblyName>();
    
            var reflectionDomain = AppDomain.CreateDomain("Nancy Reflection Domain");
    
            foreach (var assemblyName in assemblyNames)
            {
                Assembly assembly;
                if (reflectionDomain.TryLoadAssembly(assemblyName, out assembly))
                {
                    var references = assembly.GetReferencedAssemblies();
    
                    foreach (var reference in references)
                    {
                        if (AssemblyName.ReferenceMatchesDefinition(reference, CurrentAssemblyName))
                        {
                            assembliesToLoad.Add(assemblyName);
                        }
                    }
                }
            }
    
            AppDomain.Unload(reflectionDomain);
    
            return assembliesToLoad.ToArray();
        }
    
        private static IEnumerable<Assembly> LoadAssemblies(this AppDomain appDomain, IEnumerable<AssemblyName> assemblyNames)
        {
            var loadedAssemblies = new List<Assembly>();
    
            foreach (var assemblyName in assemblyNames)
            {
                Assembly assembly;
                if (appDomain.TryLoadAssembly(assemblyName, out assembly))
                {
                    loadedAssemblies.Add(assembly);
                }
            }
    
            return loadedAssemblies.ToArray();
        }
    
        private static bool TryLoadAssembly(this AppDomain appDomain, AssemblyName assemblyName, out Assembly assembly)
        {
            try
            {
                assembly = appDomain.Load(assemblyName);
                return true;
            }
            catch (Exception)
            {
                assembly = null;
                return false;
            }
        }
    }
    
    

    external by Raf  252  1  4  0

    Draft for Assembly Loading in a mixed netstandard/netcore environment

    Draft for Assembly Loading in a mixed netstandard/netcore environment: gistfile1.txt
    // Read additional notes at the end of the file
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection.Metadata;
    
    #if NET462
    #endif
    #if NETCORE
    using System.Runtime.Loader;
    #endif
    
    using System.Reflection;
    
    namespace ConsoleTest
    {
        public class AssemblyLoader
        {
            private static readonly string NetStandard = ".NETStandard";
            private static readonly string NetFramework = ".NETFramework";
            private static readonly string NetCoreApp = ".NETCoreApp";
    
            private System.IO.DirectoryInfo _dependenciesPath;
            private System.IO.FileInfo[] _dependencyFiles;
    
            public AssemblyLoader(string dependenciesPath)
            {
                _dependenciesPath = new System.IO.DirectoryInfo(dependenciesPath);
                _dependencyFiles = _dependenciesPath.GetFiles("*.dll", System.IO.SearchOption.AllDirectories);
    
                System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += AssemblyResolving;
            }
    
            private Assembly AssemblyResolving(System.Runtime.Loader.AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName)
            {
                var fileInfo = _dependencyFiles.Where(f => f.Name.StartsWith(assemblyName.Name)).FirstOrDefault();
                if (fileInfo == null)
                {
                    return null;
                }
    
                var assembly = LoadFrom(fileInfo.FullName);
                return assembly;
            }
    
            public static IList<Type> GetTypesInheriting<T>(string path)
            {
                Assembly assembly = LoadFrom(path);
                if (assembly == null)
                {
                    return new List<Type>();
                }
    
                IList<Type> types;
                try
                {
                    types = assembly.GetTypes()
                        .Where(t => typeof(T).IsAssignableFrom(t))
                        .ToList();
                }
                catch (System.Reflection.ReflectionTypeLoadException err)
                {
                    Console.WriteLine($"Error loading {path}");
                    foreach (var exception in err.LoaderExceptions)
                    {
                        Console.WriteLine($"{exception.Message}");
                    }
    
                    Console.WriteLine();
                    types = new List<Type>();
                }
                catch (Exception err)
                {
                    Console.WriteLine($"Error loading {path}");
                    Console.WriteLine(err.Message);
                    types = new List<Type>();
                }
    
                return types;
            }
    
            public static Assembly LoadFrom(string path)
            {
                var allowedFrameworks = AllowedFrameworks(path);
                Assembly assembly = null;
                try
                {
    
    #if NETCORE
                if(allowedFrameworks.RunsOnNetCore)
                {
                    assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                }
    #endif
    #if NET462
                    if (allowedFrameworks.RunsOnNetFramework)
                    {
                        assembly = Assembly.LoadFrom(path);
                    }
    #endif
                }
                catch (Exception)
                {
                    return null;
                }
    
                return assembly;
            }
    
            public static (bool RunsOnNetCore, bool RunsOnNetFramework) AllowedFrameworks(string path)
            {
                using (var fileReader = System.IO.File.OpenRead(path))
                {
                    using (var peReader = new System.Reflection.PortableExecutable.PEReader(fileReader))
                    {
                        var metadataReader = peReader.GetMetadataReader(MetadataReaderOptions.Default);
                        var attributeValue = GetTargetFrameworkAttributeValue(metadataReader);
                        var frameworkAndVersion = GetFrameworkAndVersion(attributeValue);
    
                        return
                            (frameworkAndVersion.Framework == NetStandard || frameworkAndVersion.Framework == NetCoreApp,
                            frameworkAndVersion.Framework == NetStandard || frameworkAndVersion.Framework == NetFramework);
                    }
                }
            }
    
            private static string ReadBlob(MetadataReader metadataReader, BlobHandle blobHandle)
            {
                var blobReader = metadataReader.GetBlobReader(blobHandle);
                var str = blobReader.ReadUTF16(blobReader.Length);
                return str;
            }
    
            private static IList<string> GetReferences(MetadataReader metadataReader)
            {
                var references = metadataReader.AssemblyReferences
                    .OfType<AssemblyReferenceHandle>()
                    .Select(h => metadataReader.GetAssemblyReference(h))
                    .Select(a => metadataReader.GetString(a.Name))
                    .ToList();
    
                return references;
            }
    
            private static (string Framework, Version Version) GetFrameworkAndVersion(string targetFrameworkAttributeValue)
            {
                if (string.IsNullOrEmpty(targetFrameworkAttributeValue))
                {
                    // can't find the attribute ... assume is .net framework
                    return (NetFramework, new Version("0.0.0.0"));
                    //throw new ArgumentException("Invalid TargetFrameworkAttribute Value");
                }
    
                string[] parts = targetFrameworkAttributeValue.Split(',');
                if (parts.Length != 2)
                {
                    throw new ArgumentException("Invalid TargetFrameworkAttribute Value: comma separator not found");
                }
    
                var version = "Version=v";
                if (!parts[1].StartsWith(version) || parts[1].Length <= version.Length)
                {
                    throw new ArgumentException("Invalid TargetFrameworkAttribute Value: The second part of the value should contain the Version string");
                }
    
                return (parts[0], new Version(parts[1].Substring(version.Length)));
            }
    
            // "System.Runtime.Versioning", "TargetFrameworkAttribute", ".NETStandard,Version=v1.4"
            // "System.Runtime.Versioning", "TargetFrameworkAttribute", ".NETFramework,Version=v4.6.2"
            // "System.Runtime.Versioning", "TargetFrameworkAttribute", ".NETCoreApp,Version=v1.1"
            private static string GetTargetFrameworkAttributeValue(MetadataReader metadataReader)
            {
                var attributeValue = metadataReader.GetAssemblyDefinition().GetCustomAttributes()
                            .Select(h => metadataReader.GetCustomAttribute(h))
                            .Select(a => TryGetAttributeNameAsStrings(metadataReader, a))
                            .Where(a => a.IsSuccess && a.TypeNamespace == "System.Runtime.Versioning" && a.TypeName == "TargetFrameworkAttribute")
                            .Select(a => a.ValueString)
                            .FirstOrDefault();
    
                return attributeValue;
            }
    
            // https://github.com/dotnet/corefx/blob/bffef76f6af208e2042a2f27bc081ee908bb390b/src/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Metadata.cs
            private static (bool IsSuccess, string TypeNamespace, string TypeName, string ValueString)
                TryGetAttributeNameAsStrings(MetadataReader reader, CustomAttribute attr)
            {
                var res = TryGetAttributeName(reader, attr);
                if (!res.IsSuccess)
                {
                    return (false, null, null, null);
                }
    
                var valueResult = GetStringAttributeArgumentValue(reader, attr);
                return (true, reader.GetString(res.typeNamespaceHandle), reader.GetString(res.typeNameHandle), valueResult.Value);
            }
    
            private static (bool IsSuccess, StringHandle typeNamespaceHandle, StringHandle typeNameHandle)
                TryGetAttributeName(MetadataReader reader, CustomAttribute attr)
            {
                EntityHandle ctorHandle = attr.Constructor;
                switch (ctorHandle.Kind)
                {
                    case HandleKind.MemberReference:
                        EntityHandle container = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
                        if (container.Kind == HandleKind.TypeReference)
                        {
                            TypeReference tr = reader.GetTypeReference((TypeReferenceHandle)container);
                            return (true, tr.Namespace, tr.Name);
                        }
                        break;
    
                    case HandleKind.MethodDefinition:
                        MethodDefinition md = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle);
                        TypeDefinition td = reader.GetTypeDefinition(md.GetDeclaringType());
                        return (true, td.Namespace, td.Name);
                }
    
                // Unusual case, potentially invalid IL
                return (false, default(StringHandle), default(StringHandle));
            }
    
            private static (bool IsSuccess, string Value) GetStringAttributeArgumentValue(MetadataReader reader, CustomAttribute attr)
            {
                EntityHandle ctorHandle = attr.Constructor;
                BlobHandle signature;
                switch (ctorHandle.Kind)
                {
                    case HandleKind.MemberReference:
                        signature = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Signature;
                        break;
                    case HandleKind.MethodDefinition:
                        signature = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).Signature;
                        break;
                    default:
                        // Unusual case, potentially invalid IL
                        return (false, null);
                }
    
                BlobReader signatureReader = reader.GetBlobReader(signature);
                BlobReader valueReader = reader.GetBlobReader(attr.Value);
    
                const ushort Prolog = 1; // two-byte "prolog" defined by ECMA-335 (II.23.3) to be at the beginning of attribute value blobs
                if (valueReader.ReadUInt16() == Prolog)
                {
                    SignatureHeader header = signatureReader.ReadSignatureHeader();
                    int parameterCount;
                    if (header.Kind == SignatureKind.Method &&                               // attr ctor must be a method
                        !header.IsGeneric &&                                                 // attr ctor must be non-generic
                        signatureReader.TryReadCompressedInteger(out parameterCount) &&      // read parameter count
                        parameterCount == 1 &&                                               // attr ctor must have 1 parameter
                        signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.Void && // attr ctor return type must be void
                        signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.String) // attr ctor first parameter must be string
                    {
                        return (true, valueReader.ReadSerializedString());
                    }
                }
    
                return (false, null);
            }
        }
    }
    
    // Referenced packages:
    // - System.Reflection.Metadata (1.4.2)
    // - System.Runtime.Loader (4.3.0)
    //
    // This source is not yet complete and will not probably work under nestandard
    // because it is still missing the AssemblyResolve event.
    
    
    

    external by Carlos Osoria  8  0  2  0

    EntityFrameworkContext is the class that dynamically loads its configuration from the assembly

    EntityFrameworkContext is the class that dynamically loads its configuration from the assembly: EntityFrameworkContext.cs
    public class EntityFrameworkContext<TContext> : DbContext, IEntityFrameworkContext where TContext : DbContext
    {
    	public ObjectContext ObjectContext { get { return ((IObjectContextAdapter)this).ObjectContext; } }
    
    	protected EntityFrameworkContext() : base()
    	{
    		Database.SetInitializer<TContext>(null);
    	}
    
    	protected EntityFrameworkContext(string nameOrConnectionString) : base(nameOrConnectionString)
    	{
    		Database.SetInitializer<TContext>(null);
    	}
    
    	public IDbSet<TEntity> GetDbSetOf<TEntity>() where TEntity : class
    	{
    		return base.Set<TEntity>();
    	}
    	
    	public void MarkAsAdded(object entity)
    	{
    		Entry(entity).State = DataEntityState.Added;
    	}
    
    	public void MarkAsModified(object entity)
    	{
    		Entry(entity).State = DataEntityState.Modified;
    	}
    
    	public void MarkAsDeleted(object entity)
    	{
    		Entry(entity).State = DataEntityState.Deleted;
    	}
    
    	public void MarkAsUnchanged(object entity)
    	{
    		Entry(entity).State = DataEntityState.Unchanged;
    	}
    
    	public void ExtendQueryTimeout()
    	{
    		ObjectContext.CommandTimeout = 180;
    	}
    
    	protected override void OnModelCreating(DbModelBuilder modelBuilder)
    	{
    		LoadDynamicModelConfiguration(modelBuilder);
    	}
    
    	protected virtual void LoadDynamicModelConfiguration(DbModelBuilder modelBuilder)
    	{
    		foreach (var modelConfigType in GetDynamicModelConfigurationTypes())
    		{
    
    			dynamic modelConfig = Activator.CreateInstance(modelConfigType);
    			modelBuilder.Configurations.Add(modelConfig);
    		}
    	}
    
    	protected virtual IEnumerable<Type> GetDynamicModelConfigurationTypes()
    	{
    		var types = Assembly.GetAssembly(GetType())
    							.GetTypes()
    							.GetOpenGenericDecendants(typeof(DynamicEntityTypeConfiguration<>))
    							.Where(t => t.Namespace == GetType().Namespace);
    		return types;
    	}
     }
    
    

    external by Sigge  1  0  2  0

    Loading an external .NET Standard 2.0 assembly with blazor

    In a Blazor app, I want to load an external assembly and execute a method. For this, I have created a new ASP.Net Core webapplication using the Blazor template. Then, in a Razor Page (which will be compiled and executed by browser/wasm) I use reflection to load the assembly and run the method (based on code found here) // download external assemb
    /* 
    After doing some further investigation, I've concluded that my problem is that my external library is not properly linked to the mono.net dependencies. This is why, when you build a Blazor app, it is compiled a second time to /dist/_framework/_bin.
    
    I've found three possible solutions to this problem:
    
     1. Turn the external class library into a Blazor Web app
    
    This way, your app will automatically be converted to a mono-compatible assembly when built. A simple peek in to a Blazor .csproj shows the dependencies needed to achieve this. For it to work, I had to change the .csproj of my external assembly:
    
    from a default netstandard library:
     */
    <Project Sdk="Microsoft.NET.Sdk">
        <PropertyGroup>
            <TargetFramework>netstandard2.0</TargetFramework>
        </PropertyGroup>
    </Project>
    
    
    /* 
    into a web app:
     */
    <Project Sdk="Microsoft.NET.Sdk.Web">
        <PropertyGroup>
            <TargetFramework>netstandard2.0</TargetFramework>
            <RunCommand>dotnet</RunCommand>
            <LangVersion>7.3</LangVersion>
        </PropertyGroup>
        <ItemGroup>
            <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.7.0" PrivateAssets="all" />
        </ItemGroup>
    </Project>
    
    
    /* 
    These are the only dependencies needed. On build, the compatible assembly will be found in the /dist/_framework/_bin folder. It can then be loaded using the methods described in the question.
    
    This works, but feels a bit hacky because the only reason we're turning the library into a web app is so that it can compile itself into a properly linked assembly.
    
     2. Load the netstandard2.0 mono facade
    
    Another solution is to unzip the Nuget Package from Microsoft.AspNetCore.Blazor.Build and grab the netstandard.dll. It's found in the tools\mono\bcl\Facades folder. Now, when doing the following in the main Blazor app:
     */
    var netstandard = await client.GetByteArrayAsync("http://localhost:62633/_framework/netstandard.dll");
    var externallib = await client.GetByteArrayAsync("http://localhost:62633/_framework/MyCustomLib.dll");
    AppDomain.CurrentDomain.Load(netstandard);
    var assembly = AppDomain.CurrentDomain.Load(externallib);
    
    
    /* 
    then the unmodified netstandard 2.0 library MyCustomLib will be loaded without errors.
    
    
    No need to change it to a web app
    This works, but it feels even hackier than the first solution, unsure whether this will fail later along the way...
    
    
     3. Use the Blazor Build tools
    
    The Blazor Build tools, currently found here, they have a ResolveRuntimeDependenciesCommand command for the CLI which seems to do exactly what a blazor web app is doing when it spits output to /_framework/_bin. 
    I'm still looking at how this could be used to convert a "non blazor-webapp" assembly into a mono-compatible one.
    
    Feel free to comment or answer with additional information. I'm leaving this question open until a "cleaner" solution is found.
     */
    
    • Public Snippets
    • Channels Snippets