AppDomain.Load Méthode

Définition

Charge Assembly dans ce domaine d'application.Loads an Assembly into this application domain.

Surcharges

Load(Byte[])

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

Load(AssemblyName)

Charge Assembly en fonction de son AssemblyName.Loads an Assembly given its AssemblyName.

Load(String)

Charge Assembly en fonction de son nom complet.Loads an Assembly given its display name.

Load(Byte[], Byte[])

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. Les octets bruts représentant les symboles de Assembly sont également chargés.The raw bytes representing the symbols for the Assembly are also loaded.

Load(AssemblyName, Evidence)
Obsolète.
Obsolète.

Charge Assembly en fonction de son AssemblyName.Loads an Assembly given its AssemblyName.

Load(String, Evidence)
Obsolète.
Obsolète.

Charge Assembly en fonction de son nom complet.Loads an Assembly given its display name.

Load(Byte[], Byte[], Evidence)
Obsolète.
Obsolète.

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. Les octets bruts représentant les symboles de Assembly sont également chargés.The raw bytes representing the symbols for the Assembly are also loaded.

Load(Byte[])

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly);
public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly);
public System.Reflection.Assembly Load (byte[] rawAssembly);
member this.Load : byte[] -> System.Reflection.Assembly
abstract member Load : byte[] -> System.Reflection.Assembly
override this.Load : byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte()) As Assembly

Paramètres

rawAssembly
Byte[]

Tableau de type byte qui est une image au format COFF contenant un assembly émis.An array of type byte that is a COFF-based image containing an emitted assembly.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Exceptions

rawAssembly a la valeur null.rawAssembly is null.

rawAssembly n’est pas un assembly valide.rawAssembly is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et rawAssembly a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Exemples

L’exemple suivant illustre l’utilisation du chargement d’un assembly brut.The following sample demonstrates the use of loading a raw assembly.

Pour que cet exemple de code s’exécute, vous devez fournir le nom complet de l’assembly.For this code example to run, you must provide the fully qualified assembly name. Pour plus d’informations sur la façon d’obtenir le nom complet de l’assembly, consultez noms d’assemblys.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

   static void InstantiateMyType(AppDomain domain) {
      try {
     // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Remarques

À partir de .NET Framework 4.NET Framework 4 , le niveau de confiance d’un assembly chargé à l’aide de cette méthode est le même que le niveau de confiance du domaine d’application.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Load(AssemblyName)

Charge Assembly en fonction de son AssemblyName.Loads an Assembly given its AssemblyName.

public:
 System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef);
public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef);
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef);
member this.Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
abstract member Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName) As Assembly

Paramètres

assemblyRef
AssemblyName

Objet qui décrit l'assembly à charger.An object that describes the assembly to load.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Exceptions

assemblyRef a la valeur null.assemblyRef is null.

assemblyRef est introuvable.assemblyRef is not found.

assemblyRef n’est pas un assembly valide.assemblyRef is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et assemblyRef a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Remarques

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Si une version de l’assembly demandé est déjà chargée, cette méthode retourne l’assembly chargé, même si une version différente est demandée.If a version of the requested assembly is already loaded, this method returns the loaded assembly, even if a different version is requested.

Il n’est pas recommandé de fournir un nom d’assembly partiel pour assemblyRef .Supplying a partial assembly name for assemblyRef is not recommended. (Un nom partiel omet une ou plusieurs de la culture, de la version ou du jeton de clé publique.(A partial name omits one or more of culture, version, or public key token. Pour les surcharges qui prennent une chaîne au lieu d’un AssemblyName objet, « MyAssembly, version = 1.0.0.0 » est un exemple de nom partiel et « myAssembly, version = 1.0.0.0, culture = neutral, PublicKeyToken = 18ab3442da84b47 » est un exemple de nom complet.) L’utilisation de noms partiels a un effet négatif sur les performances.For overloads that take a string instead of an AssemblyName object, "MyAssembly, Version=1.0.0.0" is an example of a partial name and "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18ab3442da84b47" is an example of a full name.) Using partial names has a negative effect on performance. En outre, un nom d’assembly partiel peut charger un assembly à partir de la Global Assembly Cache uniquement s’il existe une copie exacte de l’assembly dans le répertoire de base de l’application ( BaseDirectory ou AppDomainSetup.ApplicationBase ).In addition, a partial assembly name can load an assembly from the global assembly cache only if there is an exact copy of the assembly in the application base directory (BaseDirectory or AppDomainSetup.ApplicationBase).

Si l' AppDomain objet actuel représente le domaine A d’application et que la Load méthode est appelée à partir du domaine d’application B , l’assembly est chargé dans les deux domaines d’application.If the current AppDomain object represents application domain A, and the Load method is called from application domain B, the assembly is loaded into both application domains. Par exemple, le code suivant se charge MyAssembly dans le nouveau domaine d’application ChildDomain et également dans le domaine d’application dans lequel le code s’exécute :For example, the following code loads MyAssembly into the new application domain ChildDomain and also into the application domain where the code executes:

AppDomain^ ad = AppDomain::CreateDomain("ChildDomain");
ad->Load("MyAssembly");
AppDomain ad = AppDomain.CreateDomain("ChildDomain");
ad.Load("MyAssembly");
Dim ad As AppDomain  = AppDomain.CreateDomain("ChildDomain")
ad.Load("MyAssembly")

L’assembly est chargé dans les deux domaines, car Assembly ne dérive pas de MarshalByRefObject , et par conséquent, la valeur de retour de la Load méthode ne peut pas être marshalée.The assembly is loaded into both domains because Assembly does not derive from MarshalByRefObject, and therefore the return value of the Load method cannot be marshaled. Au lieu de cela, le common language runtime tente de charger l’assembly dans le domaine d’application appelant.Instead, the common language runtime tries to load the assembly into the calling application domain. Les assemblys qui sont chargés dans les deux domaines d’application peuvent être différents si les paramètres de chemin d’accès pour les deux domaines d’application sont différents.The assemblies that are loaded into the two application domains might be different if the path settings for the two application domains are different.

Notes

Si la AssemblyName.Name propriété et la propriété sont toutes les deux AssemblyName.CodeBase définies, la première tentative de chargement de l’assembly utilise le nom complet (y compris la version, la culture, et ainsi de suite, comme retourné par la Assembly.FullName propriété).If both the AssemblyName.Name property and the AssemblyName.CodeBase property are set, the first attempt to load the assembly uses the display name (including version, culture, and so on, as returned by the Assembly.FullName property). Si le fichier est introuvable, la CodeBase propriété est utilisée pour Rechercher l’assembly.If the file is not found, the CodeBase property is used to search for the assembly. Si l’assembly est trouvé à l’aide CodeBase de, le nom complet est mis en correspondance avec l’assembly.If the assembly is found using CodeBase, the display name is matched against the assembly. Si la correspondance échoue, une FileLoadException exception est levée.If the match fails, a FileLoadException is thrown.

Load(String)

Charge Assembly en fonction de son nom complet.Loads an Assembly given its display name.

public:
 System::Reflection::Assembly ^ Load(System::String ^ assemblyString);
public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString);
public System.Reflection.Assembly Load (string assemblyString);
member this.Load : string -> System.Reflection.Assembly
abstract member Load : string -> System.Reflection.Assembly
override this.Load : string -> System.Reflection.Assembly
Public Function Load (assemblyString As String) As Assembly

Paramètres

assemblyString
String

Nom complet de l'assembly.The display name of the assembly. Consultez FullName.See FullName.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Exceptions

assemblyString a la valeur null.assemblyString is null

assemblyString est introuvable.assemblyString is not found.

assemblyString n’est pas un assembly valide.assemblyString is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et assemblyString a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Remarques

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Load(Byte[], Byte[])

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. Les octets bruts représentant les symboles de Assembly sont également chargés.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore);
public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[]? rawSymbolStore);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore);
member this.Load : byte[] * byte[] -> System.Reflection.Assembly
abstract member Load : byte[] * byte[] -> System.Reflection.Assembly
override this.Load : byte[] * byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte()) As Assembly

Paramètres

rawAssembly
Byte[]

Tableau de type byte qui est une image au format COFF contenant un assembly émis.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Tableau de type byte contenant les octets bruts représentant les symboles de l'assembly.An array of type byte containing the raw bytes representing the symbols for the assembly.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Exceptions

rawAssembly a la valeur null.rawAssembly is null.

rawAssembly n’est pas un assembly valide.rawAssembly is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et rawAssembly a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Exemples

L’exemple suivant illustre l’utilisation du chargement d’un assembly brut.The following sample demonstrates the use of loading a raw assembly.

Pour que cet exemple de code s’exécute, vous devez fournir le nom complet de l’assembly.For this code example to run, you must provide the fully qualified assembly name. Pour plus d’informations sur la façon d’obtenir le nom complet de l’assembly, consultez noms d’assemblys.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

   static void InstantiateMyType(AppDomain domain) {
      try {
     // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Remarques

À partir de .NET Framework 4.NET Framework 4 , le niveau de confiance d’un assembly chargé à l’aide de cette méthode est le même que le niveau de confiance du domaine d’application.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Load(AssemblyName, Evidence)

Avertissement : Obsolète

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Avertissement : Obsolète

Use an overload that does not take an Evidence parameter

Charge Assembly en fonction de son AssemblyName.Loads an Assembly given its AssemblyName.

public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef, System::Security::Policy::Evidence ^ assemblySecurity);
public:
 System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef, System::Security::Policy::Evidence ^ assemblySecurity);
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName, assemblySecurity As Evidence) As Assembly

Paramètres

assemblyRef
AssemblyName

Objet qui décrit l'assembly à charger.An object that describes the assembly to load.

assemblySecurity
Evidence

Preuve de chargement de l'assembly.Evidence for loading the assembly.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Attributs

Exceptions

assemblyRef a la valeur null.assemblyRef is null

assemblyRef est introuvable.assemblyRef is not found.

assemblyRef n’est pas un assembly valide.assemblyRef is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et assemblyRef a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Remarques

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Load(String, Evidence)

Avertissement : Obsolète

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Avertissement : Obsolète

Use an overload that does not take an Evidence parameter

Charge Assembly en fonction de son nom complet.Loads an Assembly given its display name.

public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString, System::Security::Policy::Evidence ^ assemblySecurity);
public:
 System::Reflection::Assembly ^ Load(System::String ^ assemblyString, System::Security::Policy::Evidence ^ assemblySecurity);
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyString As String, assemblySecurity As Evidence) As Assembly

Paramètres

assemblyString
String

Nom complet de l'assembly.The display name of the assembly. Consultez FullName.See FullName.

assemblySecurity
Evidence

Preuve de chargement de l'assembly.Evidence for loading the assembly.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Attributs

Exceptions

assemblyString a la valeur null.assemblyString is null

assemblyString est introuvable.assemblyString is not found.

assemblyString n’est pas un assembly valide.assemblyString is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et assemblyString a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

Remarques

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Load(Byte[], Byte[], Evidence)

Avertissement : Obsolète

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.

Avertissement : Obsolète

Use an overload that does not take an Evidence parameter

Charge Assembly avec l'image au format COFF (Common Object File Format) contenant un Assembly émis.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. Les octets bruts représentant les symboles de Assembly sont également chargés.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore, System::Security::Policy::Evidence ^ securityEvidence);
public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore, System::Security::Policy::Evidence ^ securityEvidence);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")>]
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte(), securityEvidence As Evidence) As Assembly

Paramètres

rawAssembly
Byte[]

Tableau de type byte qui est une image au format COFF contenant un assembly émis.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Tableau de type byte contenant les octets bruts représentant les symboles de l'assembly.An array of type byte containing the raw bytes representing the symbols for the assembly.

securityEvidence
Evidence

Preuve de chargement de l'assembly.Evidence for loading the assembly.

Retours

Assembly

Assembly chargé.The loaded assembly.

Implémente

Attributs

Exceptions

rawAssembly a la valeur null.rawAssembly is null.

rawAssembly n’est pas un assembly valide.rawAssembly is not a valid assembly.

- ou --or- La version 2.0 ou ultérieure du Common Language Runtime est actuellement chargée et rawAssembly a été compilé avec une version ultérieure.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

L’opération est tentée sur un domaine d’application non chargé.The operation is attempted on an unloaded application domain.

Un assembly ou un module a été chargé à deux reprises avec deux preuves différentes.An assembly or module was loaded twice with two different evidences.

securityEvidence n’est pas un null.securityEvidence is not null. Quand la stratégie CAS héritée n’est pas activée, securityEvidence doit être null.When legacy CAS policy is not enabled, securityEvidence should be null.

Exemples

L’exemple suivant illustre l’utilisation du chargement d’un assembly brut.The following sample demonstrates the use of loading a raw assembly.

Pour que cet exemple de code s’exécute, vous devez fournir le nom complet de l’assembly.For this code example to run, you must provide the fully qualified assembly name. Pour plus d’informations sur la façon d’obtenir le nom complet de l’assembly, consultez noms d’assemblys.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

   static void InstantiateMyType(AppDomain domain) {
      try {
     // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Remarques

À partir de .NET Framework 4.NET Framework 4 , le niveau de confiance d’un assembly chargé à l’aide de cette méthode est le même que le niveau de confiance du domaine d’application.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Cette méthode doit être utilisée uniquement pour charger un assembly dans le domaine d’application actuel.This method should be used only to load an assembly into the current application domain. Cette méthode est fournie à des fins de commodité pour les appelants d’interopérabilité qui ne peuvent pas appeler la Assembly.Load méthode statique.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Pour charger des assemblys dans d’autres domaines d’application, utilisez une méthode telle que CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Pour plus d’informations communes à toutes les surcharges de cette méthode, consultez la Load(AssemblyName) surcharge de méthode.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

S’applique à