4

I have a class that has the following...

public class Client<T> : IClient where T : IClientFactory, new()
{
    public Client(int UserID){}
}

and another class that implements IClientFactory

public class Client : IClientFactory

If the dll is referenced then I can easily do this to instantiate it.

var data = new namespace.Client<namespace.OtherDLL.Client>(1);

But obviously if I try to do it with a loaded assembly this will fail as it doesn't know the type. I keep reading around to use Reflection to do it. But I try to implement those ideas and have failed. Here is an article about it. Can I pass a type object to a generic method?

Assembly myDllAssembly = Assembly.LoadFile(project.Path + project.Assembly);

Type type = myDllAssembly.GetType("Migration.Application.Client");

var data = new namespace.Client<type>(1);

Any help on this would be great, since I'm trying to just use a configuration file to allow me to easily drop DLL when they are ready to the client and just modify the config file to make things work.

Community
  • 1
  • 1
GameScrub
  • 177
  • 1
  • 11
  • possible duplicate of [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – nawfal Jan 17 '14 at 15:49

1 Answers1

1

You need to call the method using reflection:

var type = typeof(Client<>).MakeGenericType(type);
var data = (IClient)Activator.CreateInstance(type, 1)
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • I think you meant `MakeGenericType` – McGarnagle Dec 10 '12 at 18:07
  • @dbaseman: To me `var data = namespace.Client(1);` looks like a method call. But you are correct, the rest of the question looks more like he forgot the `new` there... – Daniel Hilgarth Dec 10 '12 at 18:08
  • `Assembly myDllAssembly = Assembly.LoadFile(project.Path + project.Assembly);` `Type genericClassType = myDllAssembly.GetType("GEC.Migration.SWOCS.Application.Client");` `var type = GEC.Migration.FileManager.GetType("Client").MakeGenericMethod(genericClassType);` `var data = (IClient)Activator.CreateInstance(type, userID);` I seem to be having problems with the GetType() Says it's not found – GameScrub Dec 10 '12 at 18:14