我正在尝试实现如下所示的UoW: http://blog.iannelson.systems/wcf-global-exception-handling/
但我不能为我的生活弄清楚如何用Autofac连接它。我完全不知道从哪里开始。
我使用http://autofac.readthedocs.org/en/latest/integration/wcf.html
使用Autofac让WCF正常工作但要注入或添加IEndpointBehavior?不知道......
如果有更好的方法来实施UoW,我想听听。
修改
现在我刚刚完成了:
builder.RegisterType(typeof (UnitOfWork))
.As(typeof (IUnitOfWork))
.InstancePerLifetimeScope()
.OnRelease(x =>
{
Trace.WriteLine("Comitted of UoW");
((IUnitOfWork) x).Commit();
// OnRelease inhibits the default Autofac Auto-Dispose behavior so explicitly chain to it
x.Dispose();
});
虽然我不知道这是否是一种可接受的方式,但看起来像是黑客:(
编辑2:
似乎不可能在WCF中运行UoW:/
编辑3:
我在这里发布了我的解决方案:http://www.philliphaydon.com/2011/11/06/unit-of-work-with-wcf-and-autofac/
答案 0 :(得分:2)
我找到了这个问题的解决方案,只有在没有错误的情况下才会提交工作单元。
在Autofac
中将工作单位注册为InstancePerLifetimeScope builder.RegisterType(typeof (UnitOfWork))
.As(typeof (IUnitOfWork)).InstancePerLifetimeScope();
然后我创建了一个组合的EndpointBehavior和一个ErrorHandler。
public class UnitOfWorkEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
var unitOfWorkInstanceHandler = new UnitOfWorkInstanceHandler();
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(unitOfWorkInstanceHandler);
endpointDispatcher.DispatchRuntime.InstanceContextInitializers.Add(unitOfWorkInstanceHandler);
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
protected override object CreateBehavior()
{
return new UnitOfWorkEndpointBehavior();
}
public override Type BehaviorType
{
get { return typeof (UnitOfWorkEndpointBehavior); }
}
}
public class UnitOfWorkInstanceHandler : IInstanceContextInitializer, IErrorHandler
{
private bool _doCommit = true;
public void Initialize(InstanceContext instanceContext, Message message)
{
instanceContext.Closing += CommitUnitOfWork;
}
void CommitUnitOfWork(object sender, EventArgs e)
{
//Only commit if no error has occured
if (_doCommit)
{
//Resolve the UnitOfWork form scope in Autofac
OperationContext.Current.InstanceContext.Extensions.Find<AutofacInstanceContext>().Resolve<IUnitOfWork>().Commit();
}
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
_doCommit = false;
}
public bool HandleError(Exception error)
{
_doCommit = false;
return false;
}
}
在web.config中注册端点行为
<system.serviceModel>
...
<extensions>
<behaviorExtensions>
<add name="UnitOfWork" type="Namespace.UnitOfWorkBehavior, Namespace"/>
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="">
<UnitOfWork/>
</behavior>
</endpointBehaviors>
...
</behaviors>
...
</system.serviceModel>