Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# encapsulation: Get types from other project

I need to explain a bit to get to the problem.

I have 3 projects:

Project 1 can see project 2 and 3.

Project 2 can see project 3.

Project 3 is a dll and the others are apps.

I had to design a class with a lot of subclasses. The subclasses all have a method which is declared as abstract in the base, so they all have to use it. They need to get distributed in all projects, because the code in methode directly interacts with the project.

The abstract base classes are in Project 3, the subclasses are in 2 and 1. There's the problem I have:

This is the method I wrote:

   public static IEnumerable<Type> GetSubClasses(Type typ)
   {
       IEnumerable<Type> subclasses =
       from type in Assembly.GetAssembly(typ).GetTypes()
       where type.IsSubclassOf(typ) && !type.IsAbstract
       select type;
       return subclasses;
   }

I'm trying to get all subclasses of the type but when I do, I only get the subclasses from the current project. For example, if I try to get them from project1, I dont get the subclasses from project 2.

How do I do that? I know I can get an assembly reference from project 2 but it has no GetAssembly(Type t) method, with the help of that I'm getting all the subclasses. If it would be the same I just had to do the same there.

My second question is, is there an easier way at all? It's a bit.."large" having those classes in many projects, maybe there's a solution to get them into one. Like I said, the code of the methode they all need to have, needs to directly interact with the project they are in.


1 Answers

The problem is you're calling Assembly.GetTypes(). That gives you only the classes in that particualr assembly. If you have Assembly objects for all three assemblies, you can do something like

assem1.GetTypes()
.Concat(assem2.GetTypes())
.Concat(assem3.GetTypes())

So the problem is how you get the three Assembly objects. From project 1 you can just say

var assem1 = typeof(SomeClassInProj1).Assembly;
var assem2 = typeof(SomeClassInProj2).Assembly;
var assem3 = typeof(SomeClassInProj3).Assembly;

In a project where you can't "see" the other assemblies, you need to load them. See the documentation of Assembly.Load.

like image 159
Jeppe Stig Nielsen Avatar answered Nov 30 '25 11:11

Jeppe Stig Nielsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!