0

在我们的项目中,我们使用城堡容器来解决依赖关系。基本上,我们为执行不同的任务提供肥皂服务。

  public interface IServiceA
   {
      public ServiceResponse Process(ServiceRequest request);
   }

   public class ServiceA : IServiceA
   {
      public ServiceResponse Process(ServiceRequest request)
     {
         /////process stuff
     }
   }

    public interface IServiceB
   {
      public ServiceResponse ReProcess(ServiceRequest request);
   }

   public class ServiceB : IServiceB
   {
      private IServiceA _svcA;
      public ServiceB ()
      {
        _svcA= Container.Get<IServiceA>(); 
      }

     public ServiceResponse ReProcess(ServiceRequest request)
     {
        ////stuff
        _svcA.Process(new ServiceRequest()); 
     }
   }

我可以重用 svcA 的 process 方法以避免臃肿的重复代码,但为此我需要在调用它的 process 方法时告诉 svcA,该调用来自 svcB 的 Reprocess 方法,以便 svcA 的 process 方法可以查看就像是

public ServiceResponse Process(ServiceRequest request)\
{
   if (calledFromSvcB)
   {
    //do stuff
   }
   //process
}

限制是我不能修改合同,这意味着 serviceA 提供的方法或其类型的签名。

我想出的唯一想法是:

 public class ServiceA : IServiceA
       {
         public bool IsCalledFromSvcB {get; set;} 
         public ServiceResponse Process(ServiceRequest request)
         {
             /////process stuff
         }
       }
 public class ServiceB : IServiceB
   {
      private IServiceA _svcA;
      public ServiceB ()
      {
        _svcA= Container.Get<IServiceA>(); 
      }

     public ServiceResponse ReProcess(ServiceRequest request)
     {
        _svcA.GetType().GetProperty("IsCalledFromSvcB ").SetValue(this, true);
        ////stuff
        _svcA.Process(new ServiceRequest()); 
     }
   }
which is really ugly. Any other ideas to inject this? 
4

1 回答 1

1

如果您可以同时处理多个请求,则在内部服务上设置属性或字段将不起作用。

第二个界面可能是一个更好的主意。就像是:

internal interface IServiceAInternal
{
    ServiceResponse ProcessFromServiceB(ServiceRequest request);
}

public class ServiceA : IServiceA, IServiceAInternal
{
    public ServiceResponse Process(ServiceRequest request)
    {
        return ProcessCore(request, false);
    }

    ServiceResponse IServiceAInternal.ProcessFromServiceB(ServiceRequest request)
    {
        return ProcessCore(request, true);
    }

    private ServiceResponse ProcessCore(ServiceRequest request, bool calledFromServiceB)
    {
        ...
    }
}

public class ServiceB : IServiceB
{
    private readonly IServiceAInternal _serviceA;

    public ServiceB()
    {
        _serviceA = Container.Get<IServiceAInternal>();
    }

    public ServiceResponse ReProcess(ServiceRequest request)
    {
        return _serviceA.ProcessFromServiceB(request);
    }
}
于 2013-02-12T18:38:08.573 回答