WCF - Autofac IOC
/// <summary> /// IOC实例提供者,基于AutoFac /// /// </summary> public class IocInstanceProvider : IInstanceProvider { Type serviceType; IContainer container; public IocInstanceProvider(Type serviceType) { this.serviceType = serviceType; container = RegisterDependency(); } private IContainer RegisterDependency() { var builder = new ContainerBuilder(); builder.RegisterType(Service1).InstancePerLifetimeScope(); //配置外部接口 builder.RegisterType<Test>().As<ITest>().SingleInstance(); return builder.Build(); } public object GetInstance(InstanceContext instanceContext, Message message) { return container.Resolve(serviceType); } public object GetInstance(InstanceContext instanceContext) { return GetInstance(instanceContext, null); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { if (instance is IDisposable) ((IDisposable)instance).Dispose(); } }
/// <summary> /// 使用IOC必须加上的特性,只能在实现类上使用 /// /// </summary> public class IocServiceBehavior : Attribute, IServiceBehavior { public void AddBindingParameters(ServiceDescription serviceDescription , ServiceHostBase serviceHostBase , Collection<ServiceEndpoint> endpoints , BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { foreach (ChannelDispatcher item in serviceHostBase.ChannelDispatchers) { foreach (var ed in item.Endpoints) { if (!ed.IsSystemEndpoint) { ed.DispatchRuntime.InstanceProvider = new IocInstanceProvider(serviceDescription.ServiceType); } } } } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } }
使用:
[IocServiceBehavior] public class Service1:IService1{ //methods }