简体   繁体   中英

Activator.CreateInstance(Type) as Interface returns null

I have this as the main class of my dll:

namespace PTEmu
{

    public class DatabaseProtocol : IDatabaseProtocol
    {
      (constructors and methods)
    }
 }

This code I use to Load the DLL and create an instance of the class

var assembly = Assembly.LoadFrom("database\\" + file);
var t = assembly.GetType("PTEmu.DatabaseProtocol");
var protocol = Activator.CreateInstance(t) as IDatabaseProtocol;

Assembly.LoadFrom, assembly.GetType and Activator.CreateInstance itself, doesn't throw any errors.

I can't see what is wrong, sice I took this piece of code from another project that worked fine with it.

If I remove as IDatabaseProtocol , it returns an object, but not an object like the interface I want, so I can call the methods easily...

This is a problem of type identity . The identity of a type in .NET is not just the namespace name and type name. It also includes the assembly from which it came. So the mistake here is that you had two distinct interface types. One that came from your main assembly, another that came from the plugin assembly. Adding the source code file with Add Link isn't good enough, it matters which assembly the type got compiled into. Or in other words, the source code file plays no role at all in the type identity.

Notable perhaps is that this rule was changed in .NET 4. The identity of a type can be the solely determined by the value of the [Guid] attribute applied to the type. This enabled the "Embed Interop Types" feature in the properties of an assembly reference. Also known as the No PIA feature. It is however only valid on COM interface types. It put an end to having to install massive PIAs when you write code that automates Office apps.

You'll however have to do the exact equivalent of a PIA, a third assembly that defines the interface type and is referenced by both projects.

I solved my problem by adding a new project named framework that stores the interface. Then I referenced it in my two other projects.

Don't bother and don't waste your time!

  1. Create a new DIFFERENT class library for interfaces
  2. Create an interface in this new library
  3. implement the interface in your class (other project)
  4. try to re-run
  5. TAADAAAM!!!

.net need this interface to be in OTHER class library and not the same one!!

I had almost similar issue. But in my case the interface was already in a different shared class library. Solution was to set the "Copy Local" property for the shared reference project to "No".

在此处输入图像描述

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