samedi 4 novembre 2017

wcf - multiple KnowType commands - proper pattern for execution

I have a WCF service used to execute some commands from clients. I have a base class, AbstractCommand and a number of derived classes which define concrete commands.

The WCF web service has a single method void Execute(AbstractCommand command). It can accept concrete commands (classes derived from AbstractCommand) by means of the [KnownType] attribute. The commands are executed against a database via a Repository.

To simplify, let's say that commands are executed in the service something like this:

public void Excecute(AbstractCommand command) {
   // Concrete command 1
   var theCommand = command as ConcreteCommand1;
   if (theCommand != null) {
      var par1 = theCommand.Par1;
      var par2 = theCommand.Par2;
      ...
      _repository.DoSomething(par1, par2...);
      return;
   }
   // Concrete command 2
   var theCommand = command as ConcreteCommand2;
      ...

This if-branching looks a little bit scary and I want to refactor it. I'm thinking about something like this: The AbstractCommand should define and ConcreteCommands should implement a method Execute which will look like this:

public class ConcreteCommand1 : AbstractCommand {
   public int Par1 { get; set; }
   public int Par2 { get; set; }
   ...

   public void Execure(IRepository repository) {
      repository.DoSomething(Par1, Par2...);

so that in the service I no longer need to have that nasty if-branching and can do just this:

public void Excecute(AbstractCommand command) {
   command.Execure(_repository);
}

It looks fine. The only drawback with this approach is that now ConcreteCommand classes instead of just being DTOs (par1, par2...) need to define logic in them (the Execute method) and should be aware about the IRepository.

Can anybody suggest a better approach?

Aucun commentaire:

Enregistrer un commentaire