【发布时间】:2012-07-16 23:13:56
【问题描述】:
有没有办法处理 WCF 服务的构造函数抛出的异常,当该构造函数接受依赖项时,它是 IoC 容器(在本例中为 AutoFac)对依赖项的实例化导致异常?
考虑具有以下构造函数的 WCF 服务:
public InformationService(IInformationRetriever informationRetriever)
{
_informationRetriever = informationRetriever;
}
//... the service later makes use of the injected InformationRetriever
该服务使用 AutoFac WcfIntegration 和 AutofacWebServiceHostFactory(这恰好是一个 RESTful 服务)。
依赖注册在服务的 global.asax.cs 中,即:
builder.RegisterType<InformationRetriever>()
.As<IInformationRetriever>()
现在InformationRetriever 实现在其构造函数中执行一些检查,以确保一切就绪,以便能够完成其工作。当它在这个阶段发现问题时,它会抛出异常。
但是,我不希望服务的调用者收到 AutoFac 异常:
An exception was thrown while invoking the constructor ... on type InformationRetriever
实际上我正在尝试测试:
鉴于信息服务正在运行
当我调用 GetSomeInformation() 方法
并且无法实例化 InformationRetriever
那么我想返回一个友好的错误信息
并且记录实际的异常
这是我的设计问题,还是有已知的模式可以克服或防止这个问题?
我四处寻找,找不到任何关于此类问题的信息。
【问题讨论】:
标签: c# inversion-of-control autofac