.net - Dependency Injection when using the Command Pattern -
.net - Dependency Injection when using the Command Pattern -
i'm using command pattern first time. i'm little unsure how should handle dependencies.
in code below, dispatch createproductcommand
queued executed @ later time. command encapsulates info needs execute.
in case need access info store of type create product. question is, how inject dependency command can execute?
public interface icommand { void execute(); } public class createproductcommand : icommand { private string productname; public createproductcommand(string productname) { this.productname = productname; } public void execute() { // save product } } public class dispatcher { public void dispatch<tcommand>(tcommand command) tcommand : icommand { // save command queue } } public class commandinvoker { public void run() { // queue while (true) { var command = queue.dequeue<icommand>(); command.execute(); thread.sleep(10000); } } } public class client { public void createproduct(string productname) { var command = new createproductcommand(productname); var dispatcher = new dispatcher(); dispatcher.dispatch(command); } }
many thanks ben
after looking @ code recommend not using command pattern, instead using command info objects , command handler:
public interface icommand { } public interface icommandhandler<tcommand> tcommand : icommand { void handle(tcommand command); } public class createproductcommand : icommand { } public class createproductcommandhandler : icommandhandler<createproductcommand> { public void handle(createproductcommand command) { } }
this scenario more suitable cases createproductcommand might need cross application boundaries. also, can have instance of createproductcommand resolved di container dependencies configured. dispatcher, or 'message bus' invoke handler when receives command.
take here background info.
.net dependency-injection command-pattern
Comments
Post a Comment