开发者

Is there any way to clean up the following generic method using any of the new C# 4 features?

I've just modified a method for handling my DDD commands (previously it had no return type):

public static CommandResult<TReturn> Execute<TCommand, TReturn>(TCommand command) 
     where TCommand : IDomainCommand
{
    var handler = IoCFactory.GetInstance<ICommandHandler<TCommand, TReturn>>();
    return handler.Handle(command);
}

The method is fine, and does what I want it to do, however using it creates some fugly code:

CommandResult<Customer> result = 
    DomainCommands.Execute<CustomerCreateCommand, Customer>
    (
        new CustomerCreateCommand(message)
    );

Before I added the Customer return type TReturn, it was nice and tidy and the method could infer the types from its usage. However that's no longer possible.

Is there any way using any new C# features that I could rewrite the above to make it tidier, i.e. using Func, Action, Expression, etc? I'm probably expecting the imp开发者_如何学Goossible, but I'm getting fed up of writing so much code to just call a single method that used to be very simple.


One option to reduce it slightly is to have a static generic type for the type parameter that can't be inferred, allowing you to have a generic method with just one type parameter that can be inferred:

public static class DomainCommands<TReturn>
{
    public static CommandResult<TReturn> Execute<TCommand>(TCommand command) 
        where TCommand : IDomainCommand
   {
      var handler = IoCFactory.GetInstance<ICommandHandler<TCommand, TReturn>>();
      return handler.Handle(command);
   }
}

Then:

var result = DomainCommands<Customer>.Execute(new CustomerCreateCommand(msg));

It's not much nicer, but it's slightly better. Of course, if the domain command type itself could be generic, that might help - so CustomerCreateCommand would implement IDomainCommand<Customer> for example. If you still needed a nongeneric IDomainCommand, you could make IDomainCommand<T> derive from IDomainCommand.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜