服务模式 - 消除代码重复

时间:2016-08-29 23:30:26

标签: c# .net entity-framework design-patterns model-view-controller

通常,我服务层中的所有服务都遵循相同的模式:

public ApiResponseDto DoStuff (int parameter){
   var response = new ApiResponseDto();
   try{
       using (var db = new DbConext()){
           // do stuff
           // throw descriptive exceptions when needed
           return response;
       }
   }
   catch (Exception e) {
       ThrowError(e) // handles logging, verbosity per environment, etc
       response.Success = false; // etc
       return response;
   }
}

我想知道的是 - 是否有一种模式可用于消除此代码重复?在我正在开发的应用程序中使用相同的足迹大约200次,尝试以某种方式减少重复似乎是正确的。

1 个答案:

答案 0 :(得分:1)

你可以尝试一些事情:

  1. 将公共代码拉出到静态助手类中,然后在控制器方法中使用它
  2. 创建基本API控制器并从
  3. 继承

    选项1

    ......看起来像这样:

    def clock_field(clock: Clock, field: String): Any = {
      field match {
        case "hour" => clock.hour
        case "minute" => clock.minute
      }
    }
    

    然后在您的API控制器方法中:

    public static class WebHelpers
    {
        public static DTO GetHelper<T, DTO>(Func<T> getMethod)
        {
            T entity;
            try
            {
                entity = getMethod();
            }
            catch (Exception e)
            {           
                ThrowError(e); // handles logging, verbosity per environment, etc
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
            if (entity == null) throw new HttpResponseException(HttpStatusCode.NotFound);
            DTO dto = Mapper.Map<DTO>(entity); // project entity to DTO using AutoMapper (or do it manually)
            return dto;
        }
    }
    

    选项2

    ......看起来像这样:

    public EntityDto Get(int id)
    {
        return WebHelpers.GetHelper<Entity, EntityDto>(() =>
        {
            using (var db = new DbConext())
            {           
                return db.Entities.Find(id);            
            }
        });
    }
    

    然后继承:

    public abstract class BaseApiController<T, DTO>
    {
        public virtual DTO Get(int id)
        {
            T entity;
            try
            {
                using (var db = new DbConext())
                {
                    entity = db.Set<T>().Find(id);
                }
            }
            catch (Exception e)
            {
                ThrowError(e); // handles logging, verbosity per environment, etc
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
            if (entity == null) throw new HttpResponseException(HttpStatusCode.NotFound);
            DTO dto = Mapper.Map<DTO>(entity); // project entity to DTO using AutoMapper (or do it manually)
            return dto;
        }       
    }
    

    如果您使用选项2,则必须对路由进行一些讨论。