tags:

views:

41

answers:

2

I am trying to create an instance of an object inside of an AppDomain.
With the below code, I get an Exception "Type is not resolved for member"

Here is the code:

private  T GetInstance<T>(AppDomain domain, params object[] constructorArguments)
{
    string assemblyName = Assembly.GetAssembly(typeof (T)).FullName;
    string typeName = typeof (T).FullName;

    //also tried this for no-argument constructors
    //var objectHandle = domain.CreateInstance(assemblyName, typeName );

    var objectHandle = domain.CreateInstance(assemblyName, typeName, false
        , BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance
        , null, constructorArguments, null, null, null);

    //This call fails with the exception: "Type is not resolved for member"
    return (T) objectHandle.Unwrap();
}

What am I missing?

+4  A: 

Have you loaded the assembly defining type T in the domain? (You need to have the appropriate assmebly and it's dependencies loaded in the appdoiman before you can attempt to instantiate a type). Try instantiatiing a type defined in mscorlib or system to see if this is the issue

MaLio
In this particular case, the type I am testing with is in the same assembly as the GetInstance method, so it shouldn't be necessary to explicitly load the assembly (though it is something to keep in mind).
Nathan
Thats all good and well. The assembly is loaded into the current appdomain, but not into the 'domain' appdomain. If you set domain = System.AppDomain.CurrentDomain; does it work? If so, then be sure to ensure that the assembly containing GetInstance is loaded into the domain appdomain.
MaLio
Additionally (as per your comment in the other answer) I was not always using MarshalByRef objects.
Nathan
A: 

Hmm... I think MaLio is right. Additionally i would suggest, that you use a IoC in each Domain, like AutoFac. with that, you could even register Factories for a class. or different lifetimes. i do not like, that you have the object in first hand, and then pass it as a string. there has to be a better way.

cRichter
I see no problem with the strings. The type is used to determine the string, so there are no included literals. Nathan should be mindful though to return (pass over the remoting boundry) only MarshalByRef objects, else their type (+dependencies) needs to loaded into the current domain also. MarshalByRefs are passed as proxies.
MaLio