从对象外部设置属性值

时间:2013-02-12 18:25:46

标签: c#

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

  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的进程方法,以便不会出现臃肿的重复代码,但为此我需要在调用其进程方法时告诉svcA,调用来自svcB的Reprocess方法,以便svcA'进程方法可以看起来像

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? 

1 个答案:

答案 0 :(得分: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);
    }
}