AppDomain.AssemblyResolve Событие
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Происходит при сбое разрешения сборки.
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
Тип события
Реализации
- Атрибуты
Примеры
В следующем примере показано AssemblyResolve событие.
Для выполнения этого примера кода необходимо указать полное имя сборки. Сведения о том, как получить полное имя сборки, см. в разделе "Имена сборок".
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
Комментарии
Это ответственность ResolveEventHandler за то, что это событие возвращает сборку, указанную ResolveEventArgs.Name свойством, или возвращает значение NULL, если сборка не распознается. Сборка должна быть загружена в контекст выполнения; Если он загружается в контекст только для отражения, загрузка, которая вызвала сбой этого события.
Инструкции по использованию этого события см. в разделе "Разрешение загрузки сборок".
Начиная с .NET Framework 4, ResolveEventArgs.RequestingAssembly свойство возвращает сборку, запрашивающую загрузку сборки, которую не удалось устранить. Например, загрузчик может не загрузить зависимость запрашивающей сборки, так как запрашиваемая сборка и ее зависимость не находятся в пути проверки. Зная удостоверение запрашивающей сборки, может оказаться полезным при поиске зависимости или при определении правильной версии, если доступно несколько версий зависимости. Дополнительные сведения см. в разделе ResolveEventArgs.RequestingAssembly.
Это важно
Начиная с .NET Framework 4 ResolveEventHandler , событие создается для всех сборок, включая сборки ресурсов. В более ранних версиях событие не было создано для сборок ресурсов. Если операционная система локализована, обработчик может вызываться несколько раз: один раз для каждого языка и региональных параметров в резервной цепочке.
Для этого события ResolveEventArgs.Name свойство возвращает имя сборки перед применением политики.
Это важно
Если для этого события зарегистрировано несколько обработчиков событий, обработчики событий вызываются в порядке, пока обработчик событий не возвращает значение, которое не nullявляется. Последующие обработчики событий игнорируются.
Дополнительные сведения об обработке событий см. в разделе "Обработка и создание событий".