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