Reputation: 16182
I'm trying to eliminate a call from my API in which the end-user has to pass Assembly.GetExecutingAssembly()
in their code, currently my code looks lke the following.
public static Dictionary<int, Packet> Packets { get; private set; }
public static void Init()
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType == typeof(Packet))
{
...
}
}
}
However this only gets all of the classes that are available in the API.dll, and none of the classes from the project that's using the .dll are included,
However if I pass it as a paramter, like so:
public static void Init(Assembly assembly) {}
it loads everything just fine, is this intended behaviour, is there a way to do this all in the background without the end-user ever having to worry about the Assmebly call?
In a nutshell - I have a .dll file that people will be using in their projects, I want to get all of the classes from the project that's using the .dll, not all of the classes inside of the .dll
Upvotes: 1
Views: 137
Reputation: 31394
Why are you limiting your clients to have to define their Packet
classes in a single assembly? What if a client wants to implement different types of Packet
classes in different assemblies? What if someone wants to do run time code generation and create a Packet
class at runtime?
Your API shouldn't care where or how Packet classes are defined. It should just expose an interface that will allow clients to register new Packet
types directly. That will give clients the maximum flexibility.
Now it would be appropriate to provider helper methods so that clients could register types from assemblies or from the calling assemblies.
Something like:
class PacketRegistration {
public void RegisterPacketType(Type packetType) {...}
public void RegisterPacketType<TPacket>() where TPacket:Packet {
RegisterPacket(typeof(TPacket));
}
public void RegisterPacketTypesFromAssembly(Assembly assembly) {...}
public void RegisterPacketTypesFromCurrentAssembly() {
RegisterPacketTypesFromAssembly(Assembly.GetCallingAssembly());
}
Upvotes: 0