简体   繁体   中英

assembly.CreateInstance returns null

I'm working with assembly.CreateInstance, and it returns null, while it was fine using it with a different project with the same DLL file "assembly file", Can you please suggest reasons when and why it returns null?Please this is urgent??

Edit

The type I'm searching for has a default constructor, but it implements another interface, like this. Project1, has the interface A and makes the DLL which contains the new type let it be typeB which implements A. Project2, has the same interface A and use the "CreateInstance" method to locate the type typeB, but here the CreateInstance returns null, any suggestions?

I doubt it applies here, but there is 1 edge-case wher CreateInstance returns null (namely Nullable<T> ), and one extreme corner-case ( ProxyAttribute , discussed here ) where a regular class can construct to null .

But more likely:

  • it doesn't exist (name wrong, perhaps)
  • you are using as , and the interface isn't implemented (perhaps the interface is declared in two different assemblies; it counts separately as different interfaces in each, even if the name and namespace are identical)

From the edit, it sounds like the last point; you should have the interface defined once only , and a reference between assemblies so that other assemblies can see (and implement) that interface.

Please see the documentation:

http://msdn.microsoft.com/en-us/library/aa329906(v=VS.71).aspx

It is returning null because the type you are passing in is not found. If you post your code perhaps we can be more specific!

The function returns a null if it cannot find the type specified or if the type does not have a default constructor. See the documentation on MSDN.

You need to make sure that your code is looking for the right assembly and type in the right place and that you have the appropriate permissions.

It just so happens that Assembly.CreateInstance will return null if it is called by a class that resides in the same assembly as the requested type. I guess the .NET folks thought you would never need to do such a thing, which was a very wrong assumption.

The Assembly.CreateInstance call must be made from a class residing outside the assembly that contains the object-type you are trying to create.

Go figure.

更可靠的方法是使用Activator.CreateInstance并直接传入类型。

As a follow up to the other replies, it can also occur because dependent assembly cannot be found (or loaded). Possible reasons include file not existing, different versions, strong name verification, permissions, etc.

您可以尝试使用程序集绑定日志查看器 (fuslogvw)来尝试查看是否存在任何失败的绑定来解决您的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM