如何在c#中更好地装饰异步方法?

时间:2016-06-02 10:03:56

标签: c# asynchronous decorator

有一个界面

public interface ISomeInterface
{
     Task<int> SomeMethodAsync();
     Task<int> OtherMethodAsync();
}

以及实现它的类

public class SomeClass : ISomeInterface
{
    public async Task<int> SomeMethodAsync() {... return x; }
    public async Task<int> OtherMethodAsync() {... return y; }
}

我想装饰这个类,为它的一些方法添加一些功能(例如记录)

public class LogDecoratedSomeClass : ISomeInterface
{
     private readonly ISomeInterface _decoratee;
     private readonly ILogger _logger;

     public LogDecoratedSomeClass(ISomeInterface decoratee, ILogger logger)
     {
         if (decoratee == null) throw new ArgumentNullException("decoratee");
         if (logger == null) throw throw new ArgumentNullException("logger");
         _decoratee = dedcoratee;
         _logger = logger;
     }

     public async Task<int> SomeMethodAsync()
     {
          _logger.log( <some message> );
          var result = await _decoratee.SomeMethodAsync();
          _logger.log( <even more messages> );
          return result;
     }

     public async Task<int> OtherMethodAsync()
     {
          return await _decoratee.OtherMethodAsync();
     }
}

最后一个方法可以写成

public Task<int> OtherMethodAsync()
{
    return _decoratee.OtherMethodAsync();
}

这两种方式中的哪一种比另一种更好?

感谢

更新:

webapi方法怎么样?

public class SomeController : ApiController
{
     private readonly ISomeInterface _service;

     <constructor ...>

     [HttpGet]
     public async Task<int> Get()
     {
          return await _service.SomeMethodAsync();
     }
}

0 个答案:

没有答案