【发布时间】:2018-10-23 18:23:53
【问题描述】:
我试图在我的 wcf 项目中实现一个简单的通用错误处理程序,但问题是我想注入一个服务(使用 autofac)以保存所有异常。我到处找,我什么也没找到。我将 Autofac 与 Autofac.Integration.Wcf 一起使用。
public class GlobalErrorHandler : IErrorHandler
{
private IErrorService ErrorService;
public GlobalErrorHandler(IErrorService errorService)
{
this.ErrorService = errorService;
}
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
//log the error using the service
}
}
public class ErrorHandlerExtension : BehaviorExtensionElement, IServiceBehavior
{
public override Type BehaviorType
{
get { return GetType(); }
}
protected override object CreateBehavior()
{
return this;
}
private IErrorHandler GetInstance()
{
return new GlobalErrorHandler();
}
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandlerInstance = GetInstance();
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
{
dispatcher.ErrorHandlers.Add(errorHandlerInstance);
}
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
if (endpoint.Contract.Name.Equals("IMetadataExchange") &&
endpoint.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
continue;
foreach (OperationDescription description in endpoint.Contract.Operations)
{
if (description.Faults.Count == 0)
{
throw new InvalidOperationException("FaultContractAttribute not found on this method");
}
}
}
}
}
web.config
<extensions>
<behaviorExtensions>
<add name="errorHandler"
type="Base.WCF.Helpers.Error_Handler.ErrorHandlerExtension, Base.WCF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
global.asax
var builder = new ContainerBuilder();
builder.RegisterType<Base.WCF.BaseService>();
builder.RegisterType<ErrorService>().As<IErrorService>();
var IOCContainer = builder.Build();
AutofacHostFactory.Container = IOCContainer;
我找不到任何方法可以让我在 IErrorHandler 中注入服务,因为我无法解决它的依赖关系。问题是我必须通过 ApplyDispatchBehavior 注册自定义 IErrorHandler。我也在我的 ErrorHandlerExtension 中尝试了构造函数注入,但它也没有工作。我的 wcf 服务方法中的所有其他注入也可以正常工作。
有什么方法可以在我的 IErrorHandler 中注入 IErrorService 吗?
编辑
根据 Travis 的回答,我还必须解决我的其他存储库注入问题,因此我使用了以下方法
using (var scope = AutofacHostFactory.Container.BeginLifetimeScope())
{
var svc = scope.Resolve<IErrorHistoryService>();
scope.Resolve<IErrorHistoryRepository>();
scope.Resolve<IUnitOfWork>();
svc.AddError(new ErrorLog_BO());
svc.SaveError();
}
【问题讨论】: