Код ошибки system typeloadexception

I’m getting the following error on one of my referenced assemblies:

Could not load type 'System.Func`2' from assembly 'MyAssembly, ...

My first instinct was to see what MSDN had to say about it:

TypeLoadException is thrown when the
common language runtime cannot find
the assembly, the type within the
assembly, or cannot load the type.

It appears to be is saying that the CLR simply can’t find the type? That might make more sense if this wasn’t something that was in mscorlib. This was all built on top of .NET4 with VS2010, so there’s no mono or other weird library issues. What’s going on?

ΩmegaMan's user avatar

ΩmegaMan

29.6k12 gold badges100 silver badges122 bronze badges

asked Apr 17, 2011 at 2:46

kertosis's user avatar

3

I received this error after refactoring. I had two projects compiling to DLLs with the same name.

Check the «Assembly name» in the project’s properties’ «Application» section.

answered Mar 13, 2014 at 15:55

Ian Warburton's user avatar

Ian WarburtonIan Warburton

15.2k23 gold badges107 silver badges189 bronze badges

6

The problem is that you have a mismatch in your versions. Make sure all your assemblies are compiled for .NET 4.

answered Apr 17, 2011 at 3:44

Gabe's user avatar

GabeGabe

85k12 gold badges140 silver badges238 bronze badges

1

I’m not sure about your specific scenario, but the Assembly Binding Log Viewer (fuslogvw) is usually very helpful in debugging type load issues. More details at http://msdn.microsoft.com/en-us/library/e74a18c4.aspx

John Saunders's user avatar

John Saunders

161k26 gold badges247 silver badges397 bronze badges

answered Apr 17, 2011 at 2:54

Ragesh's user avatar

RageshRagesh

2,8202 gold badges26 silver badges36 bronze badges

3

You may also get this if you change the assembly you’re trying to load but still have an old version in the GAC. It tries to load the GAC’ed version not what you reference in your VS project.

answered Nov 4, 2015 at 22:49

Jay's user avatar

JayJay

13.9k4 gold badges42 silver badges70 bronze badges

I got this error when I moved a class from one project to another in a cleanup effort. After looking at all other possible reasons, reloaded each of the projects in my solution and everything worked.

  1. Right Click on the project name in solution explorer
  2. Select Unload Project
  3. Right Click on the project name in solution explorer
  4. Select Reload Project

answered Jul 30, 2014 at 12:59

RWL01's user avatar

RWL01RWL01

4661 gold badge5 silver badges17 bronze badges

This problem may occur if you have different versions of NuGet packages installed across different projects. To identify these cases,

  1. Right-click the solution in Solution Explorer and select «Manage Nuget Packages for Solution»
  2. Select the «Consolidate» tab
  3. For any identified packages, identify the version you want and click «Install» to consolidate the package to that version.

answered Mar 25, 2019 at 5:38

Daniel Elkington's user avatar

Daniel ElkingtonDaniel Elkington

2,6207 gold badges23 silver badges35 bronze badges

I encountered this exception when I refactored to move some classes to their own library, and referenced a different version of the library it’s trying to load in the new library (acquired with NuGet) than I had been using in the original project.

The thing that fixed it was to open the NuGet Manager in the old project, and update the appropriate package to be the same version I was using in my new library.

answered Sep 15, 2017 at 17:33

Aaron Averett's user avatar

I used the procedure by RWL01 above — unload and reload the project and it worked.

All my NuGet packages were up to date and there was no option to consolidate them.

I closed VS 2022 and reopened VS and the Solution. Under the assumption that possibly there was something in memory or the GAC had not been updated due to VS being open.

I restarted my emulator(s) at the same time.

answered Mar 29 at 19:04

rick's user avatar

I’m getting the following error on one of my referenced assemblies:

Could not load type 'System.Func`2' from assembly 'MyAssembly, ...

My first instinct was to see what MSDN had to say about it:

TypeLoadException is thrown when the
common language runtime cannot find
the assembly, the type within the
assembly, or cannot load the type.

It appears to be is saying that the CLR simply can’t find the type? That might make more sense if this wasn’t something that was in mscorlib. This was all built on top of .NET4 with VS2010, so there’s no mono or other weird library issues. What’s going on?

ΩmegaMan's user avatar

ΩmegaMan

29.6k12 gold badges100 silver badges122 bronze badges

asked Apr 17, 2011 at 2:46

kertosis's user avatar

3

I received this error after refactoring. I had two projects compiling to DLLs with the same name.

Check the «Assembly name» in the project’s properties’ «Application» section.

answered Mar 13, 2014 at 15:55

Ian Warburton's user avatar

Ian WarburtonIan Warburton

15.2k23 gold badges107 silver badges189 bronze badges

6

The problem is that you have a mismatch in your versions. Make sure all your assemblies are compiled for .NET 4.

answered Apr 17, 2011 at 3:44

Gabe's user avatar

GabeGabe

85k12 gold badges140 silver badges238 bronze badges

1

I’m not sure about your specific scenario, but the Assembly Binding Log Viewer (fuslogvw) is usually very helpful in debugging type load issues. More details at http://msdn.microsoft.com/en-us/library/e74a18c4.aspx

John Saunders's user avatar

John Saunders

161k26 gold badges247 silver badges397 bronze badges

answered Apr 17, 2011 at 2:54

Ragesh's user avatar

RageshRagesh

2,8202 gold badges26 silver badges36 bronze badges

3

You may also get this if you change the assembly you’re trying to load but still have an old version in the GAC. It tries to load the GAC’ed version not what you reference in your VS project.

answered Nov 4, 2015 at 22:49

Jay's user avatar

JayJay

13.9k4 gold badges42 silver badges70 bronze badges

I got this error when I moved a class from one project to another in a cleanup effort. After looking at all other possible reasons, reloaded each of the projects in my solution and everything worked.

  1. Right Click on the project name in solution explorer
  2. Select Unload Project
  3. Right Click on the project name in solution explorer
  4. Select Reload Project

answered Jul 30, 2014 at 12:59

RWL01's user avatar

RWL01RWL01

4661 gold badge5 silver badges17 bronze badges

This problem may occur if you have different versions of NuGet packages installed across different projects. To identify these cases,

  1. Right-click the solution in Solution Explorer and select «Manage Nuget Packages for Solution»
  2. Select the «Consolidate» tab
  3. For any identified packages, identify the version you want and click «Install» to consolidate the package to that version.

answered Mar 25, 2019 at 5:38

Daniel Elkington's user avatar

Daniel ElkingtonDaniel Elkington

2,6207 gold badges23 silver badges35 bronze badges

I encountered this exception when I refactored to move some classes to their own library, and referenced a different version of the library it’s trying to load in the new library (acquired with NuGet) than I had been using in the original project.

The thing that fixed it was to open the NuGet Manager in the old project, and update the appropriate package to be the same version I was using in my new library.

answered Sep 15, 2017 at 17:33

Aaron Averett's user avatar

I used the procedure by RWL01 above — unload and reload the project and it worked.

All my NuGet packages were up to date and there was no option to consolidate them.

I closed VS 2022 and reopened VS and the Solution. Under the assumption that possibly there was something in memory or the GAC had not been updated due to VS being open.

I restarted my emulator(s) at the same time.

answered Mar 29 at 19:04

rick's user avatar

The exception that is thrown when type-loading failures occur.

TypeLoadException happens when a type could not be loaded by the CLR. This can be caused by several different issues, but here’s a list of things to try out:

EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.

Create new class which inherited from IDesignTimeDbContextFactory .

public class YourDbContext : DbContext
{
//Dbcontext implementation
}

public class YourDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
    public YourDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
        optionsBuilder.UseSqlServer("your connection string");

        return new YourDbContext(optionsBuilder.Options);
    }
}

You are using a new .net core EF which uses IHostBuilder.(in an older version like yours the provider is IWebHostBuilder).

The tools first try to obtain the service provider by invoking the Program.CreateHostBuilder(), calling Build(), then accessing the Services property.

You can learn more about Design-time DbContext Creation from Here

It may happen from a condition in your startup file or while you are injecting. for example, you have a flag that checks if some variable in appsettings is true to use inmemory database instance.

EF needs to build the model and use the DbContext without starting the application. When EF invokes methods, your config services are still null that’s why you get an error.

Make sure you have installed the package

Microsoft.EntityFrameworkCore.Tools

The accepted answer is so convincing that I almost believed this wasn’t a bug. But after doing some experiments now I can say that Level2 security is a complete mess; at least, something is really fishy.

A couple of days ago I bumped into the same issue with my libraries. I quickly created a unit test; however, I could not reproduce the problem I experienced in .NET Fiddle, while the very same code «successfully» threw the exception in a console app. In the end I found two weird ways to overcome the issue.

TL;DR: It turns out that if you use an internal type of the used library in your consumer project, then the partially trusted code works as expected: it is able to instantiate an ISerializable implementation (and a security critical code cannot be called directly, but see below). Or, which is even more ridiculous, you can try to create the sandbox again if it didn’t work for the first time…

But let’s see some code.

ClassLibrary.dll:

Let’s separate two cases: one for a regular class with security critical content and one ISerializable implementation:

public class CriticalClass
{
    public void SafeCode() { }

    [SecurityCritical]
    public void CriticalCode() { }

    [SecuritySafeCritical]
    public void SafeEntryForCriticalCode() => CriticalCode();
}

[Serializable]
public class SerializableCriticalClass : CriticalClass, ISerializable
{
    public SerializableCriticalClass() { }

    private SerializableCriticalClass(SerializationInfo info, StreamingContext context) { }

    [SecurityCritical]
    public void GetObjectData(SerializationInfo info, StreamingContext context) { }
}

One way to overcome the issue is to use an internal type from the consumer assembly. Any type will do it; now I define an attribute:

[AttributeUsage(AttributeTargets.All)]
internal class InternalTypeReferenceAttribute : Attribute
{
    public InternalTypeReferenceAttribute() { }
}

And the relevant attributes applied to the assembly:

[assembly: InternalsVisibleTo("UnitTest, PublicKey=<your public key>")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityRules(SecurityRuleSet.Level2, SkipVerificationInFullTrust = true)]

Sign the assembly, apply the key to the InternalsVisibleTo attribute and prepare for test project:

UnitTest.dll (uses NUnit and ClassLibrary):

To use the internal trick the test assembly should be signed as well. Assembly attributes:

// Just to make the tests security transparent by default. This helps to test the full trust behavior.
[assembly: AllowPartiallyTrustedCallers] 

// !!! Comment this line out and the partial trust test cases may fail for the fist time !!!
[assembly: InternalTypeReference]

Note: The attribute can be applied anywhere. In my case it was on a method in a random test class took me a couple of days to find.

Note 2: If you run all test methods together it can happen that the tests will pass.

The skeleton of the test class:

[TestFixture]
public class SecurityCriticalAccessTest
{
    private partial class Sandbox : MarshalByRefObject
    {
    }

    private static AppDomain CreateSandboxDomain(params IPermission[] permissions)
    {
        var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
        var permissionSet = GetPermissionSet(permissions);
        var setup = new AppDomainSetup
        {
            ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
        };

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        var strongNames = new List<StrongName>();
        foreach (Assembly asm in assemblies)
        {
            AssemblyName asmName = asm.GetName();
            strongNames.Add(new StrongName(new StrongNamePublicKeyBlob(asmName.GetPublicKey()), asmName.Name, asmName.Version));
        }

        return AppDomain.CreateDomain("SandboxDomain", evidence, setup, permissionSet, strongNames.ToArray());
    }

    private static PermissionSet GetPermissionSet(IPermission[] permissions)
    {
        var evidence = new Evidence();
        evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
        var result = SecurityManager.GetStandardSandbox(evidence);
        foreach (var permission in permissions)
            result.AddPermission(permission);
        return result;
    }
}

And let’s see the test cases one by one

Case 1: ISerializable implementation

The same issue as in the question. The test passes if

  • InternalTypeReferenceAttribute is applied
  • sandbox is tried to be created multiple times (see the code)
  • or, if all the test cases are executed at once and this is not the first one

Otherwise, there comes the totally inappropriate Inheritance security rules violated while overriding member... exception when you instantiate SerializableCriticalClass.

[Test]
[SecuritySafeCritical] // for Activator.CreateInstance
public void SerializableCriticalClass_PartialTrustAccess()
{
    var domain = CreateSandboxDomain(
        new SecurityPermission(SecurityPermissionFlag.SerializationFormatter), // BinaryFormatter
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
    var handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
    var sandbox = (Sandbox)handle.Unwrap();
    try
    {
        sandbox.TestSerializableCriticalClass();
        return;
    }
    catch (Exception e)
    {
        // without [InternalTypeReference] it may fail for the first time
        Console.WriteLine($"1st try failed: {e.Message}");
    }

    domain = CreateSandboxDomain(
        new SecurityPermission(SecurityPermissionFlag.SerializationFormatter), // BinaryFormatter
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
    handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
    sandbox = (Sandbox)handle.Unwrap();
    sandbox.TestSerializableCriticalClass();

    Assert.Inconclusive("Meh... succeeded only for the 2nd try");
}

private partial class Sandbox
{
    public void TestSerializableCriticalClass()
    {
        Assert.IsFalse(AppDomain.CurrentDomain.IsFullyTrusted);

        // ISerializable implementer can be created.
        // !!! May fail for the first try if the test does not use any internal type of the library. !!!
        var critical = new SerializableCriticalClass();

        // Critical method can be called via a safe method
        critical.SafeEntryForCriticalCode();

        // Critical method cannot be called directly by a transparent method
        Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
        Assert.Throws<MethodAccessException>(() => critical.GetObjectData(null, new StreamingContext()));

        // BinaryFormatter calls the critical method via a safe route (SerializationFormatter permission is required, though)
        new BinaryFormatter().Serialize(new MemoryStream(), critical);
    }

}

Case 2: Regular class with security critical members

The test passes under the same conditions as the first one. However, the issue is completely different here: a partially trusted code may access a security critical member directly.

[Test]
[SecuritySafeCritical] // for Activator.CreateInstance
public void CriticalClass_PartialTrustAccess()
{
    var domain = CreateSandboxDomain(
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess), // Assert.IsFalse
        new EnvironmentPermission(PermissionState.Unrestricted)); // Assert.Throws (if fails)
    var handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
    var sandbox = (Sandbox)handle.Unwrap();
    try
    {
        sandbox.TestCriticalClass();
        return;
    }
    catch (Exception e)
    {
        // without [InternalTypeReference] it may fail for the first time
        Console.WriteLine($"1st try failed: {e.Message}");
    }

    domain = CreateSandboxDomain(
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
    handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
    sandbox = (Sandbox)handle.Unwrap();
    sandbox.TestCriticalClass();

    Assert.Inconclusive("Meh... succeeded only for the 2nd try");
}

private partial class Sandbox
{
    public void TestCriticalClass()
    {
        Assert.IsFalse(AppDomain.CurrentDomain.IsFullyTrusted);

        // A type containing critical methods can be created
        var critical = new CriticalClass();

        // Critical method can be called via a safe method
        critical.SafeEntryForCriticalCode();

        // Critical method cannot be called directly by a transparent method
        // !!! May fail for the first time if the test does not use any internal type of the library. !!!
        // !!! Meaning, a partially trusted code has more right than a fully trusted one and is       !!!
        // !!! able to call security critical method directly.                                        !!!
        Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
    }
}

Case 3-4: Full trust versions of case 1-2

For the sake of completeness here are the same cases as the ones above executed in a fully trusted domain. If you remove [assembly: AllowPartiallyTrustedCallers] the tests fail because then you can access critical code directly (as the methods are not transparent by default anymore).

[Test]
public void CriticalClass_FullTrustAccess()
{
    Assert.IsTrue(AppDomain.CurrentDomain.IsFullyTrusted);

    // A type containing critical methods can be created
    var critical = new CriticalClass();

    // Critical method cannot be called directly by a transparent method
    Assert.Throws<MethodAccessException>(() => critical.CriticalCode());

    // Critical method can be called via a safe method
    critical.SafeEntryForCriticalCode();
}

[Test]
public void SerializableCriticalClass_FullTrustAccess()
{
    Assert.IsTrue(AppDomain.CurrentDomain.IsFullyTrusted);

    // ISerializable implementer can be created
    var critical = new SerializableCriticalClass();

    // Critical method cannot be called directly by a transparent method (see also AllowPartiallyTrustedCallersAttribute)
    Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
    Assert.Throws<MethodAccessException>(() => critical.GetObjectData(null, default(StreamingContext)));

    // Critical method can be called via a safe method
    critical.SafeEntryForCriticalCode();

    // BinaryFormatter calls the critical method via a safe route
    new BinaryFormatter().Serialize(new MemoryStream(), critical);
}

Epilogue:

Of course, this will not solve your problem with .NET Fiddle. But now I would be very surprised if it wasn’t a bug in the framework.

The biggest question to me now is the quoted part in the accepted answer. How did they come out with this nonsense? The ISafeSerializationData is clearly not a solution for anything: it is used exclusively by the base Exception class and if you subscribe the SerializeObjectState event (why isn’t that an overridable method?), then the state will also be consumed by the Exception.GetObjectData in the end.

The AllowPartiallyTrustedCallers/SecurityCritical/SecuritySafeCritical triumvirate of attributes were designed for exactly the usage shown above. It seems total nonsense to me that a partially trusted code cannot even instantiate a type regardless of the attempt using its security critical members. But it is an even bigger nonsense (a security hole actually) that a partially trusted code may access a security critical method directly (see case 2) whereas this is forbidden for transparent methods even from a fully trusted domain.

So if your consumer project is a test or another well-known assembly, then the internal trick can be used perfectly. For .NET Fiddle and other real-life sandboxed environments the only solution is reverting back to SecurityRuleSet.Level1 until this is fixed by Microsoft.


Update: A Developer Community ticket has been created for the issue.

As the accepted answer suggested:

EF calls CreateWebHostBuilder or BuildWebHost without running Main. So
Iconfiguration is null.

But instead of using a more complex factory, You can use this simple solution by overriding OnConfiguring.

public class ApplicationDbContext : DbContext
{        
    public ApplicationDbContext() {
        
    }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {            
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Chinook");
        }
    }

*Pay attention for not using the db connection string inside the source code (docs)

dotnet user-secrets set ConnectionStrings:Chinook "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook"
dotnet ef dbcontext scaffold Name=ConnectionStrings:Chinook Microsoft.EntityFrameworkCore.SqlServer

also pay attention to use only one \ in the cli command line.

I got this in a WCF service due to having an x86 build type selected, causing the bins to live under bin\x86 instead of bin. Selecting Any CPU caused the recompiled DLLs to go to the correct locations (I wont go into detail as to how this happened in the first place).

My application loads dlls and runs some reflection on them

Assembly asm = Assembly.LoadFrom("full/path/to/my.dll");
var types = asm.GetExportedTypes(); // Throws System.TypeLoadException
//Could not load type 'System.Runtime.InteropServices.StandardOleMarshalObject' from assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

and I get a System.TypeLoadException. I’m not sure why the dll (in this case Mono’s System.Windows.Form) is _exporting_ that, but it seems that I can’t even inherit from StandardOleMarshallObject, I mean, it compiles, but then at runtime fails to load
the type:

class Whatever : System.Runtime.InteropServices.StandardOleMarshalObject
{
    public Whatever(){}
}

...

var x = new Whatever();

According to the documentation StandardOleMarshallObject lives in 

System.dll, System.Runtime.InteropServices.dll

Both of which I can confirm reside in /usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.3

I’m using .net core 2.0 on OSX, fwiw.

What can I do to resolve the load error?

Thanks

Nic

Возникает такая ошибка при запуске одного интересующего меня примера с MSDN.

Сама ошибка (вывод консоли):

spoiler

Unhandled Exception:
System.TypeLoadException: Could not resolve type with token 0100000e from typeref (expected class ‘System.Security.Cryptography.ECDiffieHellmanCng’ in assembly ‘System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’)
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not resolve type with token 0100000e from typeref (expected class ‘System.Security.Cryptography.ECDiffieHellmanCng’ in assembly ‘System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’)

Ссылка на код примера на MSDN:

https://docs.microsoft.com/en-us/dotnet/api/system…

Искал решения на русскоязычных ресурсах, на англоязычных — больше всего степень отчаяния отражает вопрос человека на StackOverflow

https://stackoverflow.com/questions/56103758/getti…

Тут и много вариантов решений приведены. Поражает их спектр — от «удали папки obj и bin и пересобери проект» до «mono скоро умрет, установи windows и vs». Причем кому-то решения помогли. Но не мне.

Версия MonoDevelop 7.8.2 (build 2), версия ОС Linux Mint 19.1 Tessa, код запускал уже кажется со всеми доступными в IDE версиями .NET, но воз и ныне там — ошибка выглядит одинаково при любом раскладе. Обычные программы типа «hello world!» или домодельных классов работают без проблем, проблемы начинаются при использовании встроенных классов — в частности System.Security.Cryptography.ECDiffieHellmanCng. Дело где-то в System.Core, что-то его не видит, или видит не так — но в чем именно дело и как решить проблему я так и не понял.

Кто сталкивался с подобным, как получилось решить?

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Код ошибки status access violation как исправить
  • Код ошибки system service exception windows 11
  • Код ошибки status access violation гугл хром
  • Код ошибки system pte misuse
  • Код ошибки status access violation chrome

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: