AppDomain.Load Metodo

Definizione

Carica Assembly nel dominio applicazione.

Overload

Load(Byte[])

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato.

Load(AssemblyName)

Carica Assembly, dato il relativo AssemblyName.

Load(String)

Carica Assembly, dato il nome visualizzato.

Load(Byte[], Byte[])

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato. Vengono caricati anche i byte non elaborati che rappresentano i simboli per l'oggetto Assembly.

Load(AssemblyName, Evidence)
Obsoleti.

Carica Assembly, dato il relativo AssemblyName.

Load(String, Evidence)
Obsoleti.

Carica Assembly, dato il nome visualizzato.

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

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato. Vengono caricati anche i byte non elaborati che rappresentano i simboli per l'oggetto Assembly.

Load(Byte[])

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato.

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

Parametri

rawAssembly
Byte[]

Matrice di tipo byte costituita da un'immagine in formato COFF contenente un assembly generato.

Restituisce

Assembly caricato.

Implementazioni

Eccezioni

rawAssembly è null.

rawAssembly non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Esempio

Nell'esempio seguente viene illustrato l'uso del caricamento di un assembly non elaborato.

Per eseguire questo esempio di codice, è necessario specificare il nome completo dell'assembly. Per informazioni su come ottenere il nome completo dell'assembly, vedere Nomi assembly.

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

A partire da .NET Framework 4, il livello di attendibilità di un assembly caricato tramite questo metodo corrisponde al livello di attendibilità del dominio applicazione.

Si applica a

Load(AssemblyName)

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Carica Assembly, dato il relativo 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

Parametri

assemblyRef
AssemblyName

Oggetto che descrive l'assembly da caricare.

Restituisce

Assembly caricato.

Implementazioni

Eccezioni

assemblyRef è null.

assemblyRef non trovata.

assemblyRef non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Commenti

Questo metodo deve essere usato solo per caricare un assembly nel dominio applicazione corrente. Questo metodo viene fornito per praticità per i chiamanti di interoperabilità che non possono chiamare il metodo statico Assembly.Load . Per caricare assembly in altri domini applicazione, usare un metodo come CreateInstanceAndUnwrap.

Se è già stata caricata una versione dell'assembly richiesto, questo metodo restituisce l'assembly caricato, anche se è richiesta una versione diversa.

Non è consigliabile specificare un nome di assembly parziale per assemblyRef . Un nome parziale omette una o più impostazioni cultura, versione o token di chiave pubblica. Per gli overload che accettano una stringa anziché un AssemblyName oggetto , "MyAssembly, Version=1.0.0.0" è un esempio di nome parziale e "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18ab3442da84b47" è un esempio di nome completo. L'uso di nomi parziali ha un effetto negativo sulle prestazioni. Inoltre, un nome di assembly parziale può caricare un assembly dalla Global Assembly Cache solo se è presente una copia esatta dell'assembly nella directory di base dell'applicazione (BaseDirectory o AppDomainSetup.ApplicationBase).

Se l'oggetto corrente AppDomain rappresenta il dominio Aapplicazione e il Load metodo viene chiamato dal dominio Bapplicazione , l'assembly viene caricato in entrambi i domini applicazione. Ad esempio, il codice seguente viene caricato MyAssembly nel nuovo dominio ChildDomain applicazione e anche nel dominio dell'applicazione in cui viene eseguito il codice:

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

L'assembly viene caricato in entrambi i domini perché Assembly non deriva da MarshalByRefObjecte pertanto il valore restituito del Load metodo non può essere sottoposto a marshalling. Common Language Runtime tenta invece di caricare l'assembly nel dominio dell'applicazione chiamante. Gli assembly caricati nei due domini applicazione potrebbero essere diversi se le impostazioni del percorso per i due domini applicazione sono diverse.

Nota

Se vengono impostate sia la AssemblyName.Name proprietà che la AssemblyName.CodeBase proprietà , il primo tentativo di caricare l'assembly usa il nome visualizzato (inclusa la versione, le impostazioni cultura e così via, come restituito dalla Assembly.FullName proprietà ). Se il file non viene trovato, la CodeBase proprietà viene utilizzata per cercare l'assembly. Se l'assembly viene trovato usando CodeBase, il nome visualizzato viene confrontato con l'assembly. Se la corrispondenza ha esito negativo, viene generata un'eccezione FileLoadException .

Si applica a

Load(String)

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Carica Assembly, dato il nome visualizzato.

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

Parametri

assemblyString
String

Nome visualizzato dell'assembly. Vedere FullName.

Restituisce

Assembly caricato.

Implementazioni

Eccezioni

assemblyString è null

assemblyString non trovata.

assemblyString non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

Si applica a

Load(Byte[], Byte[])

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato. Vengono caricati anche i byte non elaborati che rappresentano i simboli per l'oggetto Assembly.

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

Parametri

rawAssembly
Byte[]

Matrice di tipo byte costituita da un'immagine in formato COFF contenente un assembly generato.

rawSymbolStore
Byte[]

Matrice di tipo byte contenente i byte non elaborati che rappresentano i simboli per l'assembly.

Restituisce

Assembly caricato.

Implementazioni

Eccezioni

rawAssembly è null.

rawAssembly non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Esempio

Nell'esempio seguente viene illustrato l'uso del caricamento di un assembly non elaborato.

Per eseguire questo esempio di codice, è necessario specificare il nome completo dell'assembly. Per informazioni su come ottenere il nome completo dell'assembly, vedere Nomi assembly.

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

A partire da .NET Framework 4, il livello di attendibilità di un assembly caricato tramite questo metodo corrisponde al livello di attendibilità del dominio applicazione.

Si applica a

Load(AssemblyName, Evidence)

Attenzione

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.

Carica Assembly, dato il relativo 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);
[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);
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
Public Function Load (assemblyRef As AssemblyName, assemblySecurity As Evidence) As Assembly

Parametri

assemblyRef
AssemblyName

Oggetto che descrive l'assembly da caricare.

assemblySecurity
Evidence

Evidenza per il caricamento dell'assembly.

Restituisce

Assembly caricato.

Implementazioni

Attributi

Eccezioni

assemblyRef è null

assemblyRef non trovata.

assemblyRef non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

Si applica a

Load(String, Evidence)

Attenzione

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.

Carica Assembly, dato il nome visualizzato.

public:
 virtual 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);
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
Public Function Load (assemblyString As String, assemblySecurity As Evidence) As Assembly

Parametri

assemblyString
String

Nome visualizzato dell'assembly. Vedere FullName.

assemblySecurity
Evidence

Evidenza per il caricamento dell'assembly.

Restituisce

Assembly caricato.

Implementazioni

Attributi

Eccezioni

assemblyString è null

assemblyString non trovata.

assemblyString non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

Si applica a

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

Attenzione

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.

Carica l'oggetto Assembly con un'immagine in formato COFF (Common Object File Format) contenente un oggetto Assembly generato. Vengono caricati anche i byte non elaborati che rappresentano i simboli per l'oggetto Assembly.

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 (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);
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
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte(), securityEvidence As Evidence) As Assembly

Parametri

rawAssembly
Byte[]

Matrice di tipo byte costituita da un'immagine in formato COFF contenente un assembly generato.

rawSymbolStore
Byte[]

Matrice di tipo byte contenente i byte non elaborati che rappresentano i simboli per l'assembly.

securityEvidence
Evidence

Evidenza per il caricamento dell'assembly.

Restituisce

Assembly caricato.

Implementazioni

Attributi

Eccezioni

rawAssembly è null.

rawAssembly non è un assembly valido per il runtime attualmente caricato.

L'operazione viene tentata in un dominio dell'applicazione non caricato.

Un assembly o un modulo è stato caricato due volte con due evidenze diverse.

securityEvidence non è null. Quando i criteri di sicurezza dall'accesso di codice legacy non sono abilitati, securityEvidence deve essere null.

Esempio

Nell'esempio seguente viene illustrato l'uso del caricamento di un assembly non elaborato.

Per eseguire questo esempio di codice, è necessario specificare il nome dell'assembly completo. Per informazioni su come ottenere il nome dell'assembly completo, vedere Nomi di assembly.

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

Commenti

Per informazioni comuni a tutti gli overload di questo metodo, vedere l'overload del Load(AssemblyName) metodo.

A partire da .NET Framework 4, il livello di attendibilità di un assembly caricato usando questo metodo corrisponde al livello di attendibilità del dominio dell'applicazione.

Si applica a