14

Update#2 as of year 2022

All these years have passed and still no good answer. Decided to revive this question.


I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).

Everything is coded from the abstract class Base till the DoSomething classes.

My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:

public async Task<Obj1<XXXX>> DoSomething1(....params....)
        {
            var action = new DoSomething1(contructParams);
            return await action.Go(....params....);
        }

I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.

Update#1 After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.

My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.

Example: I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc.... Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:

var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);

And I want to offer intellisense when I use the "CarService"....

In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.

In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:

// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
    // NO NEED OF EXTRA LINES....
}

enter image description here

11
  • 3
    Have you checked any of the existing plugin frameworks, including .NET's own MEF? Or IoC containers? Besides, you don't need inheritance when you have lambdas. You could get rid of the entire hierarchy and have each plugin create a single PluginAction class with Do1, Do2 Func<Task<T,...>> properties. Dec 21, 2016 at 9:05
  • @PanagiotisKanavos not yet, I'll take a look at MEF, thanks for pointing it out.
    – Dryadwoods
    Dec 21, 2016 at 9:09
  • softwareengineering.stackexchange.com might be a better fit for this question.
    – nvoigt
    Mar 24, 2017 at 9:17
  • @nvoigt when referring other sites, it is often helpful to point that cross-posting is frowned upon
    – gnat
    Mar 24, 2017 at 9:46
  • In my opinion you could (or should) use another design. As far as I can see, your client already knows what kind of service he needs. So why dont offer different services your client can instantiate? Like EngineStartService, EngineStopService? Maybe I am missing some crucial point but your solution seems way to complicated. Think of KISS :)
    – Andre
    Mar 29, 2017 at 9:29

6 Answers 6

3
+25

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

2

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;
}
1
  • You can replace ProvidedActions() with providedActions.Select(t => t.Name);
    – aloisdg
    Mar 28, 2017 at 13:02
0

Maybe RealProxy can help you? If you create ICarService interface which inherits IAction1 and IAction2, you can then create a proxy object which will:

  • Find all the interfaces ICarService inherits.
  • Finds realizations of these interfaces (using actions factory or reflection).
  • Creates action list for the service.
  • In Invoke method will delegate the call to one of the actions.

This way you will have intellisence as you want, and actions will be building blocks for the services. Some kind of multi-inheritance hack :)

1
  • Well, that once again relies on knowing beforehand what each service will provide and like what @Rhyous said before in the question comments, "but you want the service to provide what methods it has, not an interface". Anyway, thanks for your input.
    – Dryadwoods
    Mar 31, 2017 at 9:34
0

At this point I am really tempted to do the following:

  • Make my own Class Attribute RegisterAction (just like I wrote on my "Theoretical" example)
  • Extend the Visual Studio Build Process
  • Then on my public class LazyProgrammerSolutionTask: Microsoft.Build.Utilities.Task try to find the service classes and identify the RegisterAction attributes.
  • Then per each one, I will inject using reflection my own method (the one that I am always copying paste)... and of course get the "signature" from the corresponding target "action" class.
  • In the end, compile everything again.
  • Then my "next project" that will consume this project (library) will have the intellisence that I am looking for....
  • One thing, that I am really not sure, it how the "debug" would work on this....

Since this is also still a theoretically (BUT POSSIBLE) solution, I do not have yet a source code to share.

Meanwhile, I will leave this question open for other possible approaches.

0

I must disclose, I've never attempted anything of sorts so this is a thought experiment. A couple of wild ideas I'd explore here.

extension methods

You could declare and implement all your actions as extension methods against base class. This I believe will cover your intellisense requirements. Then you have each implementation check if it's registered against calling type before proceeding (use attributes, interface hierarchy or other means you prefer). This will get a bit noisy in intellisense as every method will be displayed on base class. And this is where you can potentially opt to filter it down by custom intellisense plugin to filter the list.

custom intellisense plugin

You could write a plugin that would scan current code base (see Roslyn), analyze your current service method registrations (by means of attributes, interfaces or whatever you prefer) and build a list of autocomplete methods that apply in this particular case.

This way you don't have to install any special plugins into your Dev environment and still have everything functional. Custom VS plugin will be there purely for convenience.

0
+100

If you have a set of actions in your project that you want to invoke, maybe you could look at it from CQS (Command Query Separation) perspective, where you can define a command and a handler from that command that actually performs the action. Then you can use a dispatcher to dispatch a command to a handler in a dynamic way. The code may look similar to:

public class StartEngine
{
    public StartEngine(...params...)
    {
    }
}

public class StartEngineHandler : ICommandHandler<StartEngine>
{
    public StartEngineHandler(...params...)
    {
    }

    public async Task Handle(StartEngine command)
    {
        // Start engine logic
    }
}

public class CommandDispatcher : ICommandDispatcher
{
    private readonly Container container;

    public CommandDispatcher(Container container) => this.container = container;

    public async Task Dispatch<T>(T command) =>
        await container.GetInstance<ICommandHandler<T>>().Handle(command);
}

// Client code
await dispatcher.Dispatch(new StartEngine(params, to, start, engine));

This two articles will give you more context on the approach: Meanwhile... on the command side of my architecture, Meanwhile... on the query side of my architecture.

There is also a MediatR library that solves similar task that you may want to check.

If the approaches from above does not fit the need and you want to "dynamically" inject actions into your services, Fody can be a good way to implement it. It instruments the assembly during the build after the IL is generated. So you could implement your own weaver to generate methods in the class decorated with your RegisterAction attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.