C# how to "register" class "plug-ins" into a service class?

For me, MEF/MAF are really something you might do last in a problem like this. First step is to work out your design. I would do the following:

  1. Implement the decorator design pattern (or a similar structural pattern of your choice). I pick decorator as that looks like what you are going for by suplimenting certain classes with shared functionality that isn't defined in those clases (ie composition seems prefered in your example as opposed to inheritance). See here http://www.dofactory.com/net/decorator-design-pattern

  2. Validate step 1 POC to work out if it would do what you want if it was added as a separate dll (ie by making a different CSProj baked in at build time).

  3. Evaluate whether MEF or MAF is for right for you (depending on how heavy weight you want to go). Compare those against other techniques like microservices (which would philosophically change your current approach).

  4. Implement your choice of hot swapping (MEF is probably the most logical based on the info you have provided).


You could use Reflection. In class Service1 define a list of BaseAction types that you want to provide:

List<Type> providedActions = new List<Type>();
providedActions.Add(typeof(DoSomething1));
providedActions.Add(typeof(DoSomething2));

Then you can write a single DoSomething method which selects the correct BaseAction at run-time:

public async Task<Obj1<XXXX>> DoSomething(string actionName, ....params....)
{
    Type t = providedActions.Find(x => x.Name == actionName);

    if (t != null)
    {
        var action = (BaseAction)Activator.CreateInstance(t);

        return await action.Go(....params....);
    }
    else
        return null;
} 

The drawback is that the Client doesn't know the actions provided by the service unless you don't implement an ad-hoc method like:

public List<string> ProvidedActions()
{
    List<string> lst = new List<string>();
    foreach(Type t in providedActions)
        lst.Add(t.Name);
    return lst;
}