开发者

How to create an object with constructor arguments in an AppDomain? (.NET 3.5)

I am trying to create an instance of an object inside of an AppDomain.

With the below code, I get an Exceptio开发者_如何学JAVAn "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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜