AppDomain.AssemblyResolve Evento
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Ocorre quando a resolução de um assembly falha.
public:
event ResolveEventHandler ^ AssemblyResolve;
public:
virtual event ResolveEventHandler ^ AssemblyResolve;
public event ResolveEventHandler? AssemblyResolve;
public event ResolveEventHandler AssemblyResolve;
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public event ResolveEventHandler AssemblyResolve;
member this.AssemblyResolve : ResolveEventHandler
[<add: System.Security.SecurityCritical>]
[<remove: System.Security.SecurityCritical>]
member this.AssemblyResolve : ResolveEventHandler
Public Custom Event AssemblyResolve As ResolveEventHandler
- Atributos
O exemplo a seguir demonstra o AssemblyResolve evento .
Para este exemplo de código ser executado, você deve fornecer o nome de assembly totalmente qualificado. Para obter informações sobre como obter o nome do assembly totalmente qualificado, consulte Nomes de assembly.
public ref class MyType
{
public:
MyType()
{
Console::WriteLine();
Console::WriteLine("MyType instantiated!");
}
};
class Test
{
public:
static void Main()
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
// This call will fail to create an instance of MyType since the
// assembly resolver is not set
InstantiateMyTypeFail(currentDomain);
currentDomain->AssemblyResolve += gcnew ResolveEventHandler(&Test::MyResolveEventHandler);
// This call will succeed in creating an instance of MyType since the
// assembly resolver is now set.
InstantiateMyTypeFail(currentDomain);
// This call will succeed in creating an instance of MyType since the
// assembly name is valid.
InstantiateMyTypeSucceed(currentDomain);
}
private:
static void InstantiateMyTypeFail(AppDomain^ domain)
{
// Calling InstantiateMyType will always fail since the assembly info
// given to CreateInstance is invalid.
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();
Console::WriteLine(e->Message);
}
}
static void InstantiateMyTypeSucceed(AppDomain^ domain)
{
try
{
String^ asmname = Assembly::GetCallingAssembly()->FullName;
domain->CreateInstance(asmname, "MyType");
}
catch (Exception^ e)
{
Console::WriteLine();
Console::WriteLine(e->Message);
}
}
static Assembly^ MyResolveEventHandler(Object^ sender, ResolveEventArgs^ args)
{
Console::WriteLine("Resolving...");
return MyType::typeid->Assembly;
}
};
int main()
{
Test::Main();
}
public class MyType
{
public MyType()
{
Console.WriteLine();
Console.WriteLine("MyType instantiated!");
}
}
class AssemblyResolveSnippet
{
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
// This call will fail to create an instance of MyType since the
// assembly resolver is not set
InstantiateMyTypeFail(currentDomain);
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
// This call will succeed in creating an instance of MyType since the
// assembly resolver is now set.
InstantiateMyTypeFail(currentDomain);
// This call will succeed in creating an instance of MyType since the
// assembly name is valid.
InstantiateMyTypeSucceed(currentDomain);
}
private static void InstantiateMyTypeFail(AppDomain domain)
{
// Calling InstantiateMyType will always fail since the assembly info
// given to CreateInstance is invalid.
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();
Console.WriteLine(e.Message);
}
}
private static void InstantiateMyTypeSucceed(AppDomain domain)
{
try
{
string asmname = Assembly.GetCallingAssembly().FullName;
domain.CreateInstance(asmname, "MyType");
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine(e.Message);
}
}
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
Console.WriteLine("Resolving...");
return typeof(MyType).Assembly;
}
}
type MyType() =
do
printfn "\nMyType instantiated!"
let instantiateMyTypeFail (domain: AppDomain) =
// Calling InstantiateMyType will always fail since the assembly info
// given to CreateInstance is invalid.
try
// You must supply a valid fully qualified assembly name here.
domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
|> ignore
with e ->
printfn $"\n{e.Message}"
let instantiateMyTypeSucceed (domain: AppDomain) =
try
let asmname = Assembly.GetCallingAssembly().FullName
domain.CreateInstance(asmname, "MyType")
|> ignore
with e ->
printfn $"\n{e.Message}"
let myResolveEventHandler _ _ =
printfn "Resolving..."
typeof<MyType>.Assembly
let currentDomain = AppDomain.CurrentDomain
// This call will fail to create an instance of MyType since the
// assembly resolver is not set
instantiateMyTypeFail currentDomain
currentDomain.add_AssemblyResolve (ResolveEventHandler myResolveEventHandler)
// This call will succeed in creating an instance of MyType since the
// assembly resolver is now set.
instantiateMyTypeFail currentDomain
// This call will succeed in creating an instance of MyType since the
// assembly name is valid.
instantiateMyTypeSucceed currentDomain
Public Class MyType
Public Sub New()
Console.WriteLine()
Console.WriteLine("MyType instantiated!")
End Sub
End Class
Class Test
Public Shared Sub Main()
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
' This call will fail to create an instance of MyType since the
' assembly resolver is not set
InstantiateMyTypeFail(currentDomain)
AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
' This call will succeed in creating an instance of MyType since the
' assembly resolver is now set.
InstantiateMyTypeFail(currentDomain)
' This call will succeed in creating an instance of MyType since the
' assembly name is valid.
InstantiateMyTypeSucceed(currentDomain)
End Sub
Private Shared Sub InstantiateMyTypeFail(domain As AppDomain)
' Calling InstantiateMyType will always fail since the assembly info
' given to CreateInstance is invalid.
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()
Console.WriteLine(e.Message)
End Try
End Sub
Private Shared Sub InstantiateMyTypeSucceed(domain As AppDomain)
Try
Dim asmname As String = Assembly.GetCallingAssembly().FullName
domain.CreateInstance(asmname, "MyType")
Catch e As Exception
Console.WriteLine()
Console.WriteLine(e.Message)
End Try
End Sub
Private Shared Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As Assembly
Console.WriteLine("Resolving...")
Return GetType(MyType).Assembly
End Function 'MyResolveEventHandler
End Class
É responsabilidade do ResolveEventHandler desse evento retornar o assembly especificado pela ResolveEventArgs.Name propriedade ou retornar nulo se o assembly não for reconhecido. O assembly deve ser carregado em um contexto de execução; se ele for carregado no contexto somente reflexão, a carga que causou a geração desse evento falhará.
Para obter diretrizes sobre o uso desse evento, consulte Resolvendo cargas de assembly.
A partir do .NET Framework 4, a ResolveEventArgs.RequestingAssembly propriedade retorna o assembly que solicitou a carga do assembly que não pôde ser resolvida. Por exemplo, o carregador pode não conseguir carregar uma dependência do assembly solicitante porque o assembly solicitante e sua dependência não estão no caminho de investigação. Saber a identidade do assembly solicitante pode ser útil para localizar a dependência ou identificar a versão correta, se mais de uma versão da dependência estiver disponível. Para obter mais informações, consulte ResolveEventArgs.RequestingAssembly.
Importante
A partir do .NET Framework 4, o ResolveEventHandler evento é gerado para todos os assemblies, incluindo assemblies de recursos. Em versões anteriores, o evento não foi gerado para assemblies de recursos. Se o sistema operacional for localizado, o manipulador poderá ser chamado várias vezes: uma vez para cada cultura na cadeia de fallback.
Para esse evento, a ResolveEventArgs.Name propriedade retorna o nome do assembly antes que a política seja aplicada.
Importante
Se mais de um manipulador de eventos estiver registrado para esse evento, os manipuladores de eventos serão chamados em ordem até que um manipulador de eventos retorne um valor que não null
seja . Manipuladores de eventos subsequentes são ignorados.
Para obter mais informações sobre como lidar com eventos, consulte Manipulando e gerando eventos.
Produto | Versões |
---|---|
.NET | Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 2.0, 2.1 |
Comentários do .NET
O .NET é um projeto código aberto. Selecione um link para fornecer comentários: