AppDomain.AssemblyResolve Evento

Definición

Se produce cuando la resolución de un ensamblado produce errores.Occurs when the resolution of an assembly fails.

public:
 virtual event ResolveEventHandler ^ AssemblyResolve;
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public event ResolveEventHandler AssemblyResolve;
member this.AssemblyResolve : ResolveEventHandler 
Public Custom Event AssemblyResolve As ResolveEventHandler 

Implementaciones

Atributos

Ejemplos

En el ejemplo siguiente se muestra el evento AssemblyResolve.The following sample demonstrates the AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

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 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 += 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;
    }
}
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

Comentarios

Es responsabilidad del ResolveEventHandler de este evento devolver el ensamblado especificado por la propiedad ResolveEventArgs.Name, o devolver null si el ensamblado no se reconoce.It is the responsibility of the ResolveEventHandler for this event to return the assembly that is specified by the ResolveEventArgs.Name property, or to return null if the assembly is not recognized. El ensamblado se debe cargar en un contexto de ejecución; Si se carga en el contexto de solo reflexión, se produce un error en la carga que hizo que se provocó este evento.The assembly must be loaded into an execution context; if it is loaded into the reflection-only context, the load that caused this event to be raised fails.

Para obtener instrucciones sobre el uso de este evento, vea resolver cargas de ensamblado.For guidance on the use of this event, see Resolving Assembly Loads.

A partir de la .NET Framework 4.NET Framework 4, la propiedad ResolveEventArgs.RequestingAssembly devuelve el ensamblado que solicitó la carga del ensamblado que no se pudo resolver.Beginning with the .NET Framework 4.NET Framework 4, the ResolveEventArgs.RequestingAssembly property returns the assembly that requested the assembly load that could not be resolved. Por ejemplo, el cargador podría no ser capaz de cargar una dependencia del ensamblado solicitante porque el ensamblado solicitante y su dependencia no están en la ruta de acceso de sondeo.For example, the loader might be unable to load a dependency of the requesting assembly because the requesting assembly and its dependency are not in the probing path. Conocer la identidad del ensamblado solicitante podría ser útil para buscar la dependencia o para identificar la versión correcta, si hay más de una versión de la dependencia disponible.Knowing the identity of the requesting assembly might be useful in locating the dependency or in identifying the correct version, if more than one version of the dependency is available. Para obtener más información, vea ResolveEventArgs.RequestingAssembly.For more information, see ResolveEventArgs.RequestingAssembly.

Importante

A partir de la .NET Framework 4.NET Framework 4, se genera el evento de ResolveEventHandler para todos los ensamblados, incluidos los ensamblados de recursos.Beginning with the .NET Framework 4.NET Framework 4, the ResolveEventHandler event is raised for all assemblies, including resource assemblies. En versiones anteriores, el evento no se producía para los ensamblados de recursos.In earlier versions, the event was not raised for resource assemblies. Si el sistema operativo está localizado, el controlador podría llamarse varias veces: una vez para cada referencia cultural de la cadena de reserva.If the operating system is localized, the handler might be called multiple times: once for each culture in the fallback chain.

Para este evento, la propiedad ResolveEventArgs.Name devuelve el nombre del ensamblado antes de que se aplique la Directiva.For this event, the ResolveEventArgs.Name property returns the assembly name before policy is applied.

Importante

Si se registra más de un controlador de eventos para este evento, se llama a los controladores de eventos en orden hasta que un controlador de eventos devuelve un valor que no es null.If more than one event handler is registered for this event, the event handlers are called in order until an event handler returns a value that isn't null. Los controladores de eventos subsiguientes se omiten.Subsequent event handlers are ignored.

Para obtener más información sobre el manejo de eventos, consulte controlar y provocar eventos.For more information about handling events, see Handling and Raising Events.

Seguridad

SecurityCriticalAttribute
Requiere plena confianza para el llamador inmediato.Requires full trust for the immediate caller. Este miembro no puede ser utilizado por código transparente o de confianza parcial.This member cannot be used by partially trusted or transparent code.

Se aplica a

Consulte también: