配置InstanceContextMode为Single时Autofac WCF集成服务异常
Autofac WCF集成:单例模式+拦截器兼容方案
问题核心
WCF服务同时配置InstanceContextMode.Single、Autofac单例注册、Autofac拦截器时无法正常运行,但任意两个组合均正常。
解决方案
1. 调整Autofac服务注册逻辑
移除服务实现类的SingleInstance()注册,改用InstancePerLifetimeScope(),确保拦截器能正常生成代理:
builder.RegisterType<MyService>() .As<IMyService>() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() .InterceptedBy(typeof(MyInterceptor));
2. 自定义Singleton实例提供器
实现IInstanceProvider,让WCF的单例实例从Autofac获取带拦截器的代理:
public class AutofacSingletonInstanceProvider : IInstanceProvider { private readonly IComponentContext _context; private readonly Type _serviceType; private object _instance; public AutofacSingletonInstanceProvider(IComponentContext context, Type serviceType) { _context = context; _serviceType = serviceType; } public object GetInstance(InstanceContext instanceContext, Message message) { return _instance ??= _context.Resolve(_serviceType); } public object GetInstance(InstanceContext instanceContext) { return GetInstance(instanceContext, null); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { // 单例模式下不释放实例 } }
3. 扩展AutofacServiceHostFactory
重写工厂类,为Singleton服务绑定自定义实例提供器:
public class CustomAutofacServiceHostFactory : AutofacServiceHostFactory { protected override AutofacServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { var host = base.CreateServiceHost(serviceType, baseAddresses); var serviceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>(); if (serviceBehavior?.InstanceContextMode == InstanceContextMode.Single) { foreach (var endpoint in host.Description.Endpoints) { endpoint.Behaviors.Add(new AutofacSingletonEndpointBehavior(Container, serviceType)); } } return host; } } public class AutofacSingletonEndpointBehavior : IEndpointBehavior { private readonly IComponentContext _context; private readonly Type _serviceType; public AutofacSingletonEndpointBehavior(IComponentContext context, Type serviceType) { _context = context; _serviceType = serviceType; } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void Validate(ServiceEndpoint endpoint) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { endpointDispatcher.DispatchRuntime.InstanceProvider = new AutofacSingletonInstanceProvider(_context, _serviceType); } }
4. 保留WCF服务的Singleton配置
服务类上维持InstanceContextMode.Single设置:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class MyService : IMyService { // 服务实现代码 }
原因说明
当WCF启用InstanceContextMode.Single时,服务实例由WCF托管并复用;而默认Autofac WCF集成的单例注册逻辑会生成独立的代理实例,两者生命周期管理冲突,导致异常。通过自定义实例提供器,让WCF的单例实例直接来自Autofac的代理生成流程,既满足单例复用需求,又能正常触发拦截器逻辑。
内容的提问来源于stack exchange,提问作者user1542652
相关产品推荐
相关产品推荐

