最近有一个项目需要在 ABP 框架中对外提供基于 SOAP 协议的服务, 自然而然想到了用 webService 和 WCF, 后来对比了一下还是使用 WCF 来进行实现.
在实现的过程中需要与数据库进行交互, 首先想到的是直接在构造函数中进行注入, 但是直接给我报了这样的这个错误
The service type provided could not be loaded as a service because it does not have a default (parameter-Less) constructor.
To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
后来百度找了几篇文章, 后来在这里找到了
解决方案:
在 WCF 中实现依赖注入得实现 IInstanceProvider 与 IServiceBehavior 这两个接口, 并让实现 IServiceBehavior 的类成为一个 Attribute(继承自 Attribute), 然后加在 WCF 服务实现类上, 就可以实现 WCF 的构造函数依赖注入.
大致实现步骤如下:
首先实现 IInstanceProvider
- public class IocInstanceProvider : IInstanceProvider
- {
- Type _serviceType;
- IocManager _container;
- public IocInstanceProvider(Type serviceType)
- {
- _serviceType = serviceType;
- _container = IocManager.Instance;//ABP 的 IoC 容器
- }
- public object GetInstance(InstanceContext instanceContext, Message message)
- {
- if (_container.IsRegistered(_serviceType))
- {
- return _container.Resolve(_serviceType);
- }
- return null;
- }
- public object GetInstance(InstanceContext instanceContext)
- {
- return GetInstance(instanceContext, null);
- }
- public void ReleaseInstance(InstanceContext instanceContext, object instance)
- {
- if (instance is IDisposable)
- ((IDisposable)instance).Dispose();
- }
- }
实现 IServiceBehavior
- public class IocServiceBehavior : System.Attribute, IServiceBehavior
- {
- #region IServiceBehavior Members
- public void ApplyDispatchBehavior(ServiceDescription serviceDescription,ServiceHostBase serviceHostBase)
- {
- foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
- {
- foreach (EndpointDispatcher ed in cd.Endpoints)
- {
- if (!ed.IsSystemEndpoint)
- {
- ed.DispatchRuntime.InstanceProvider =
- new IocInstanceProvider(serviceDescription.ServiceType);
- }
- }
- }
- }
- #endregion
- }
在你的 WCF 服务上添加属性标签
添加属性标签
最后也是最容易忘的就是注册你的 WCF 服务到 ABP 的 IoC 容器中
找到你对应的模块 (Module) 中的 PreInitialize 方法
- public override void PreInitialize()
- {
- // 你对应的 WCF 服务
- IocManager.Register<IMSSTransfer,MSSTransfer>();
- }
以上就是这些, 大功告成
来源: http://www.jianshu.com/p/3960bdde2f4e