0

Possible Duplicate:
How to use reflection to call generic Method?

I have a method with the below signature

public string Register<T>()
{
  //code
}

which can be invoked like this

var result = Register<Employee>();

my requirement is to invoke the method by reading the type T from config file,

ie: While invoking, instead of hardcoding "Employee", i should be able to supply it dynamically by reading the config file.

Any idea on how to do it?

Community
  • 1
  • 1
Brazil Nut
  • 125
  • 2
  • 8

3 Answers3

2

Well you can use reflection, specifically MakeGenericMethod, but if you don't have the type at compile time it seems better to change the method signature to Register(Type type). Then you can read the type out of the config file and pass it in directly.

Edit

If you add a reference to SimpleInjector.Extensions, you will be able to access non-generic registration methods. See NonGenericRegistrationsExtensions.cs in the source here. This will allow you to do something like this:

string typeName = GetTypeNameFromConfigFile();
Type type = Type.GetType(typeName);
container.RegisterSingle(type, type); // register as self

Then you don't need generics at all.

You might also want to read over Advanced Scenarios

default.kramer
  • 5,943
  • 2
  • 32
  • 50
1

Type parameters are needed at compile time, so in order to do this, you'd need to make use of reflection.

How do I use reflection to call a generic method?

Community
  • 1
  • 1
dwerner
  • 6,462
  • 4
  • 30
  • 44
0

On web.config

<appSettings>
<!-- The assembly name of the default type. Use the format Fully.Qualified.Class.Name, Assembly.FileName -->
<add key="DefaultType" value="MyTestApp.BusinessEntitites.Employee, MyTestApp.BusinessEntitites " />
</appSettings>

On C#:

static void Main(string[] args)
{
    Type obj = Type.GetType(ConfigurationManager.AppSettings["DefaultType"]);
    ConstructorInfo constructor = obj.GetConstructor(new Type[] { });
    var myinstance = constructor.Invoke(null);
    var result = Register<myinstance>();
}
Nathan
  • 2,705
  • 23
  • 28
  • getting Error "The type or namespace name 'obj' could not be found (are you missing a using directive or an assembly reference?)".., But i'm looking for a solution like this.. – Brazil Nut Sep 18 '12 at 21:48
  • @BrazilNut I edited my answer. Check the web.config section – Nathan Sep 18 '12 at 21:53
  • This still won't compile because `obj` is an instance of `Type`, not a compile-time type parameter. Check dwerner's answer for what you are trying to do. – default.kramer Sep 18 '12 at 21:56
  • @BrazilNut can you try this? Updated code. – Nathan Sep 18 '12 at 22:02
  • @Nathan : still it wouldn't work for the above reason "default.kramer" mentioned – Brazil Nut Sep 18 '12 at 22:08
  • have you checked this: http://stackoverflow.com/questions/7956094/use-a-string-from-a-config-file-to-initilize-a-generic-type?rq=1 – Nathan Sep 18 '12 at 22:17