Επεξεργασία

Κοινή χρήση μέσω


AppDomain.CreateInstanceFrom Method

Definition

Creates a new instance of a specified type defined in the specified assembly file.

Overloads

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)
Obsolete.

Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Object[])

Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String)

Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Caution

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 CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Creates a new instance of the specified type defined in the specified assembly file.

public:
 virtual System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityAttributes);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
[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 CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
abstract member CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
[<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 CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object(), securityAttributes As Evidence) As ObjectHandle

Parameters

assemblyFile
String

The name, including the path, of a file that contains an assembly that defines the requested type. The assembly is loaded using the LoadFrom(String) method.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. If binder is null, the default binder is used.

args
Object[]

The arguments to pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

An array of one or more attributes that can participate in activation. Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

securityAttributes
Evidence

Information used to authorize creation of typeName.

Returns

An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.

Implements

Attributes

Exceptions

assemblyFile is null.

-or-

typeName is null.

The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

-or-

securityAttributes is not null. When legacy CAS policy is not enabled, securityAttributes should be null.

The operation is attempted on an unloaded application domain.

assemblyFile was not found.

typeName was not found in assemblyFile.

No matching public constructor was found.

The caller does not have sufficient permission to call this constructor.

assemblyFile is not a valid assembly for the currently loaded runtime.

An assembly or module was loaded twice with two different evidences.

This instance is null.

Remarks

For more information about this method, see the Activator.CreateInstanceFrom method.

When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. When the assembly is loaded into the calling application domain, exceptions can occur.

  • If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • If the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

See also

Applies to

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

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

Creates a new instance of the specified type defined in the specified assembly file.

public:
 System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
public System.Runtime.Remoting.ObjectHandle? CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
member this.CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As ObjectHandle

Parameters

assemblyFile
String

The name, including the path, of a file that contains an assembly that defines the requested type. The assembly is loaded using the LoadFrom(String) method.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. If binder is null, the default binder is used.

args
Object[]

The arguments to pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

An array of one or more attributes that can participate in activation. Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.

Exceptions

assemblyFile is null.

-or-

typeName is null.

The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

The operation is attempted on an unloaded application domain.

assemblyFile was not found.

typeName was not found in assemblyFile.

No matching public constructor was found.

The caller does not have sufficient permission to call this constructor.

assemblyFile is not a valid assembly for the currently loaded runtime.

An assembly or module was loaded twice with two different evidences.

This instance is null.

Remarks

For more information, see the Activator.CreateInstanceFrom method.

When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. When the assembly is loaded into the calling application domain, exceptions can occur.

  • If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • If the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

See also

Applies to

CreateInstanceFrom(String, String, Object[])

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

Creates a new instance of the specified type defined in the specified assembly file.

public:
 System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public:
 virtual System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public System.Runtime.Remoting.ObjectHandle? CreateInstanceFrom (string assemblyFile, string typeName, object?[]? activationAttributes);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes);
member this.CreateInstanceFrom : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
abstract member CreateInstanceFrom : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String, activationAttributes As Object()) As ObjectHandle

Parameters

assemblyFile
String

The name, including the path, of a file that contains an assembly that defines the requested type. The assembly is loaded using the LoadFrom(String) method.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

activationAttributes
Object[]

An array of one or more attributes that can participate in activation. Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.

Implements

Exceptions

assemblyFile is null.

assemblyFile was not found.

typeName was not found in assemblyFile.

The caller does not have sufficient permission to call this constructor.

No matching public constructor was found.

The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

The operation is attempted on an unloaded application domain.

assemblyFile is not a valid assembly for the currently loaded runtime.

An assembly or module was loaded twice with two different evidences.

This instance is null.

Remarks

The parameterless constructor for typeName is invoked.

For more information about this method, see the Activator.CreateInstanceFrom method.

When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. When the assembly is loaded into the calling application domain, exceptions can occur.

  • If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • If the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

See also

Applies to

CreateInstanceFrom(String, String)

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

Creates a new instance of the specified type defined in the specified assembly file.

public:
 System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName);
public:
 virtual System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName);
public System.Runtime.Remoting.ObjectHandle? CreateInstanceFrom (string assemblyFile, string typeName);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName);
member this.CreateInstanceFrom : string * string -> System.Runtime.Remoting.ObjectHandle
abstract member CreateInstanceFrom : string * string -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String) As ObjectHandle

Parameters

assemblyFile
String

The name, including the path, of a file that contains an assembly that defines the requested type. The assembly is loaded using the LoadFrom(String) method.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

Returns

An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.

Implements

Exceptions

assemblyFile is null.

-or-

typeName is null.

assemblyFile was not found.

typeName was not found in assemblyFile.

The operation is attempted on an unloaded application domain.

No parameterless public constructor was found.

The caller does not have sufficient permission to call this constructor.

assemblyFile is not a valid assembly for the currently loaded runtime.

An assembly or module was loaded twice with two different evidences.

This instance is null.

Examples

The following example shows how to use the CreateInstanceFrom(String, String) method overload to create an instance of an object in a target application domain and call its methods.

The example defines the MarshalableExample class, which can be marshaled across application domain boundaries. The example builds a path to the currently executing assembly, creates a target application domain, and uses the CreateInstanceFrom(String, String) method overload to load the example assembly into the target application domain and create an instance of MarshalableExample.

Note

The path is absolute in this example, but a relative path would also work because the Assembly.LoadFrom method is used to load the assembly.

After unwrapping the object handle, the example demonstrates three ways to use an object in a target application domain:

  • Invoking a method with late binding, using reflection. This requires type information, which causes the assembly to be loaded into the application domain of the caller. (In this example, it is already loaded.)

  • Casting the object to an interface known to both the caller and the callee. If the interface is defined in the calling assembly or in a third assembly referenced by both the caller and the callee, the called assembly is not loaded into the application domain of the caller.

  • Using the object directly when its type is known to the caller. The assembly must be loaded into the application domain of the caller.

Another way to avoid loading the called assembly into the application domain of the caller is for the caller to derive from the MarshalByRefObject class and to define a method that can be run in the target application domain. That method can use reflection to examine a target assembly, because the target assembly is already loaded into the target application domain. See the example for the DynamicDirectory property.

using namespace System;

public interface class ITest
{
    void Test(String^ greeting);
};

public ref class MarshalableExample : MarshalByRefObject, ITest
{
public:
    virtual void Test(String^ greeting)
    {
        Console::WriteLine("{0} from '{1}'!", greeting,
            AppDomain::CurrentDomain->FriendlyName);
    }
};

void main()
{
    // Construct a path to the current assembly.
    String^ assemblyPath = Environment::CurrentDirectory + "\\" +
        MarshalableExample::typeid->Assembly->GetName()->Name + ".exe";

    AppDomain^ ad = AppDomain::CreateDomain("MyDomain");
 
    System::Runtime::Remoting::ObjectHandle^ oh = 
        ad->CreateInstanceFrom(assemblyPath, "MarshalableExample");

    Object^ obj = oh->Unwrap();


    // Three ways to use the newly created object, depending on how
    // much is known about the type: Late bound, early bound through 
    // a mutually known interface, or early binding of a known type.
    //
    obj->GetType()->InvokeMember("Test", 
        System::Reflection::BindingFlags::InvokeMethod, 
        Type::DefaultBinder, obj, gcnew array<Object^> { "Hello" });

    ITest^ it = (ITest^) obj;
    it->Test("Hi");

    MarshalableExample^ ex = (MarshalableExample^) obj;
    ex->Test("Goodbye");
}

/* This example produces the following output:

Hello from 'MyDomain'!
Hi from 'MyDomain'!
Goodbye from 'MyDomain'!
 */
using System;

public interface ITest
{
    void Test(string greeting);
}

public class MarshalableExample : MarshalByRefObject, ITest
{
    static void Main()
    {
        // Construct a path to the current assembly.
        string assemblyPath = Environment.CurrentDirectory + "\\" +
            typeof(MarshalableExample).Assembly.GetName().Name + ".exe";

        AppDomain ad = AppDomain.CreateDomain("MyDomain");

        System.Runtime.Remoting.ObjectHandle oh =
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample");

        object obj = oh.Unwrap();

        // Three ways to use the newly created object, depending on how
        // much is known about the type: Late bound, early bound through
        // a mutually known interface, or early binding of a known type.
        //
        obj.GetType().InvokeMember("Test",
            System.Reflection.BindingFlags.InvokeMethod,
            Type.DefaultBinder, obj, new object[] { "Hello" });

        ITest it = (ITest) obj;
        it.Test("Hi");

        MarshalableExample ex = (MarshalableExample) obj;
        ex.Test("Goodbye");
    }

    public void Test(string greeting)
    {
        Console.WriteLine("{0} from '{1}'!", greeting,
            AppDomain.CurrentDomain.FriendlyName);
    }
}

/* This example produces the following output:

Hello from 'MyDomain'!
Hi from 'MyDomain'!
Goodbye from 'MyDomain'!
 */
open System

type ITest =
    abstract Test: string -> unit

type MarshalableExample() =
    inherit MarshalByRefObject()
    
    member _.Test greeting =
        printfn $"{greeting} from '{AppDomain.CurrentDomain.FriendlyName}'!"

    interface ITest with
        member this.Test message = this.Test message 

// Construct a path to the current assembly.
let assemblyPath = 
    Environment.CurrentDirectory + "\\" + typeof<MarshalableExample>.Assembly.GetName().Name + ".exe"

let ad = AppDomain.CreateDomain "MyDomain"

let oh =
    ad.CreateInstanceFrom(assemblyPath, "MarshalableExample")

let obj = oh.Unwrap()

// Three ways to use the newly created object, depending on how
// much is known about the type: Late bound, early bound through
// a mutually known interface, or early binding of a known type.
//
obj.GetType().InvokeMember("Test",
    System.Reflection.BindingFlags.InvokeMethod,
    Type.DefaultBinder, obj, [| box "Hello" |])
|> ignore

let it = obj :?> ITest
it.Test "Hi"

let ex = obj :?> MarshalableExample
ex.Test("Goodbye")

(* This example produces the following output:

Hello from 'MyDomain'!
Hi from 'MyDomain'!
Goodbye from 'MyDomain'!
 *)
Public Interface ITest

    Sub Test(ByVal greeting As String)
End Interface

Public Class MarshalableExample 
    Inherits MarshalByRefObject
    Implements ITest

    Shared Sub Main()
    
        ' Construct a path to the current assembly.
        Dim assemblyPath As String = Environment.CurrentDirectory & "\" &
            GetType(MarshalableExample).Assembly.GetName().Name & ".exe"

        Dim ad As AppDomain = AppDomain.CreateDomain("MyDomain")
 
        Dim oh As System.Runtime.Remoting.ObjectHandle = 
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample")

        Dim obj As Object = oh.Unwrap()


        ' Three ways to use the newly created object, depending on how
        ' much is known about the type: Late bound, early bound through 
        ' a mutually known interface, or early binding of a known type.
        '
        obj.GetType().InvokeMember("Test", 
            System.Reflection.BindingFlags.InvokeMethod, 
            Type.DefaultBinder, obj, New Object() { "Hello" })

        Dim it As ITest = CType(obj, ITest) 
        it.Test("Hi")

        Dim ex As MarshalableExample = CType(obj, MarshalableExample) 
        ex.Test("Goodbye")
    End Sub

    Public Sub Test(ByVal greeting As String) Implements ITest.Test
    
        Console.WriteLine("{0} from '{1}'!", greeting,
            AppDomain.CurrentDomain.FriendlyName)
    End Sub
End Class

' This example produces the following output:
'
'Hello from 'MyDomain'!
'Hi from 'MyDomain'!
'Goodbye from 'MyDomain'!

Remarks

The parameterless constructor for typeName is invoked.

For more information, see the Activator.CreateInstanceFrom method.

When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. When the assembly is loaded into the calling application domain, exceptions can occur.

  • If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • If the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

See also

Applies to