开发者

Best way to call a configurable method

I need to figure out the best way to call a statc m开发者_开发百科ethod 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?


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜