1

我面临以下问题:

我需要从我的控制器调用我的域层;它调用一个 Web 服务方法,该方法通过引用 (ref) 接收请求。

控制器代码:

//BusinessEntityObject is a Reference-Type (BusinessEntity) object
var request = View.BusinessEntityObject; 
_workflowService.PerformAction(request);
if(request.Errors.Count != 0)
{
    View.Errors = request.Errors;
    return false;
}

领域层(WorkflowService.cs 类):

public void PerformAction(BusinessEntity request)
{
    //TryAction(System.Action action) basically wraps action in try catch and handles exceptions 
    TryAction(() =>
             {
                 _wcfClient.RequestSomething(ref request);
             });
}

IF_wcfClient.RequestSomething在返回请求对象时修改 Errors 集合具有此错误更新的错误集合。但是,一旦将控制权返回给控制器并检查了错误集合,那么我的更新就消失了。

Edit00:哦,无耻的插头,我是代表 14,我试图提出一些对我有用的问题/答案,它说我不能因为我的水平低。

Edit01:非常感谢迪伦,看到有这样一个网站来指出人们可能会错过的非常小的事情总是很好的。将值返回给我的更新代码如下所示:

领域层(WorkflowService.cs 类):

public BusinessEntity PerformAction(BusinessEntity request)
{
    //TryAction(System.Action action) basically wraps action in try catch and handles exceptions 
    TryAction(() =>
             {
                 _wcfClient.RequestSomething(ref request);
                 return request;
             });
}
4

2 回答 2

3

当您将对象传递给 WCF 服务时,它会被序列化,通过网络发送,然后在服务器上反序列化。在这种情况下,“通过 ref”传递它不会改变任何东西,如果服务器对其进行更改,它将不会被发送回调用者。只有 WCF 调用的返回值被序列化并发回。

我建议,如果您需要 WCF 服务返回任何数据,请将其打包到返回值中。

于 2011-10-28T00:36:30.570 回答
0

您的方法缺少ref修饰符PerformAction

public void PerformAction(ref BusinessEntity request)
{
    TryAction(() => _wcfClient.RequestSomething(ref request));
}

但是,进行此更改将阻止您的代码编译。您将收到以下错误:

不能在匿名方法、lambda 表达式或查询表达式中使用 ref 或 out 参数“请求”

您必须执行以下操作才能使其正常工作:

public void PerformAction(ref BusinessEntity request)
{
    var r = request;
    TryAction(() => _wcfClient.RequestSomething(ref r));
    request = r;
}

总而言之,通过引用传递请求似乎有点古怪。最好返回一个新的(或相同的)实例并在外层进行分配。

于 2011-10-28T01:24:10.160 回答