views:

279

answers:

4

In C#, I am developing several Windows Services which have some standard functionality so I have put all this common functionality into a separate referenced utility project.

I have a situation where I need to create instances of business classes which reside in my Windows Service project from the utility project using Activator.CreateInstance.

My utility project is aware of the namespace and the class name for the Type.GetType call but the type is always null and when I think about it, it won’t be able to get the type from the project it’s referenced to, or can it?

In short:

Project A references Utility Project.
Utility Project wants to create class from Project A, its aware of the namespace and class name.

Is there a Design Pattern or an approach that I should be following to achieve this functionality? Or does this look like a no, no and I should be refactoring?

Thanks for looking

+1  A: 

You need to specify the fully-qualified assembly name (including version etc, if it's strongly named) if you want Type.GetType to find a type which isn't in either mscorlib or the calling assembly.

For example:

// Prints nothing
Console.WriteLine(Type.GetType("System.Linq.Enumerable"));
// Prints the type name (i.e. it finds it)
Console.WriteLine(Type.GetType("System.Linq.Enumerable, System.Core, "
     + "Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));

Alternatively, can you make this a generic method in the utility project, and get the caller to specify the type as a type argument?

Jon Skeet
A: 

Sounds like a circular reference problem! You may need to refactor!

Stevo3000
+1  A: 

You could look into dependency injection/ioc containers.

For example create an interface in the utility library and implement that in a specific class in the windows service. Then pass an instance to the utility class. This way the utility library doesn't have know anything about the windows service.

Alex
+4  A: 

You can solve the circular reference problem using reflection, as Jon pointed out, but I suggest rethinking the design and refactoring it. Two suggestions.

  • Use interfaces to decuple A and B. (prefered solution)
  • Move the part needed by A and B into C and reference only C from A and B.
Daniel Brückner