views:

43

answers:

3

Hi there, I need to figure out the best way to call a statc method that I know only at runtime at runtime.

Every customer that use my software has a special method that return suctom string. I am thinking to put the method name in the config file and then call it at runtime.

Is it a good way?

+5  A: 

Why not a custom class implementing a given interface? It should be better, IMO.

You could put the fully qualified class name in the config, and instantiate it by reflection:

Type t = Type.GetType(type_name_from_config);

IGivenInterface obj = (IGivenInterface) Activator.CreateInstance(t);
onof
A: 

The magic of reflection!

using System.Reflection;

var type = typeof(YourStaticClass);
var customstring = type.InvokeMember
(
    "methodname",
    BindingFlags.InvokeMethod,
    Type.DefaultBinder,
    null,
    null
);

This way you can store the method name in your preferred user store as a simple string. If it's an ASP.NET site, you can use user profiles, or otherwise use isolated storage or some user-scoped application settings.

Quick Joe Smith
+1  A: 

If each customer needs to provide a string that is not static and needs to be computed at run-time, then a good solution would be to define an interface such as:

public interface ICustomerInfo
{
   string CustomerStringValue { get; }
}

and then ask each customer to provide write a class that implements this interface.

A good way to dynamically discover and load these classes at run-time is to use the .NET managed extensibility framework (only in .NET 4.0). Using MEF, you can automatically discover assemblies in a certain directory that contain types implementing a given interface. You can them use an 'Import' attribute and have MEF dynamically activate instances of these types at run-time and inject references to them into your object.

You can find more information about MEF here.

Sam