简体   繁体   English

在WCF服务实例创建期间处理异常

[英]Handle exceptions during WCF service instance creation

I am using Unity.Wcf to inject dependencies in the service class and it work fine. 我使用Unity.Wcf在服务类中注入依赖项,它工作正常。 But if I configure my dependencies incorrectly an exception is thrown by unity that it cannot build up my service instance which is correct. 但是如果我错误地配置了我的依赖项,那么Unity会抛出异常,它无法构建我的服务实例,这是正确的。 Does anyone knows where I can handle this exception to log it for example? 有谁知道我可以在哪里处理这个例外来记录它? It's much easier to check the log than debug it every time. 检查日志要比每次调试都容易得多。

Another way to capture the exception is to override the CreateServiceHost methods in the service factory. 捕获异常的另一种方法是覆盖服务工厂中的CreateServiceHost方法。 Call base.CreateServiceHost() inside of a try...catch block and use your logging component of choice to save the exception to the log. 在try ... catch块中调用base.CreateServiceHost()并使用您选择的日志记录组件将异常保存到日志中。 Other than logging the error, the behavior will be the same. 除了记录错误之外,行为将是相同的。

public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
    try {
        return base.CreateServiceHost(constructorString, baseAddresses);
    }
    catch (Exception ex) {
        // log here
        throw;
    }
}

After some investigations I have found out how the instance is created and it seems there is no way to add logging to it easily. 经过一些调查后,我发现了如何创建实例,似乎没有办法轻松添加日志记录。 The only way it to either change the source code of Unity.Wcf or to inherit few classes and override default behavior. 它唯一的方法是更改​​Unity.Wcf的源代码或继承几个类并覆盖默认行为。 For those who are interested the logic is following: UnityServiceHostFactory creates UnityServiceHost, UnityServiceHost adds behavior class UnityInstanceProvider, this UnityInstanceProvider has a GetInstance method that creates the service and does Unity resolving. 对于那些感兴趣的人,逻辑如下:UnityServiceHostFactory创建UnityServiceHost,UnityServiceHost添加行为类UnityInstanceProvider,这个UnityInstanceProvider有一个GetInstance方法,可以创建服务并进行Unity解析。 So to log something you need to do one of the following: 因此,要记录您需要执行以下操作之一:

  1. Substitute this class with yours and inherit both UnityServiceHostFactory and UnityServiceHost 用您的类替换此类并继承UnityServiceHostFactory和UnityServiceHost
  2. Get the sources and change something right in this class (UnityInstanceProvider). 获取源代码并在此类中更改正确的内容(UnityInstanceProvider)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM