我使用Autofac 1.4.5将服务依赖关系注入到我的WCF服务中.我已经阅读并遵循了
Autofac wiki page on WcfIntegration,但我的调试显示了我的WCF服务是由System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance()方法创建的,而不是由AutofacWebServiceHostFactory创建的.我究竟做错了什么?
我已经设置了我的ajax.svc文件,使其与WebHttpBinding中使用的示例类似:
<%@ ServiceHost Language="C#" Debug="true" Service="Generic.Frontend.Web.Ajax,Generic.Frontend.Web" Factory="Autofac.Integration.Wcf.AutofacWebServiceHostFactory,Autofac.Integration.Wcf" %>
我的WCF服务类Ajax是这样定义的:
namespace Generic.Frontend.Web { [ServiceContract] [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Ajax { public MapWebService MapWebService { get; set;} public Ajax() { // this constructor is being called } public Ajax(MapWebService mapWebService) { // this constructor should be called MapWebService = mapWebService; } [WebGet(ResponseFormat = WebMessageFormat.Json)] [OperationContract(Name = "mapchange")] public MapChangeResult ProcessMapChange(string args) { // use the injected service here var result = MapWebService.ProcessMapChange(args); return result; } } }
现在我已经在Global.asax.cs中使用了如上面提到的wiki所示的接线:
var builder = new ContainerBuilder(); builder.RegisterModule(new AutofacModuleWebservice()); var container = builder.Build(); AutofacServiceHostFactory.Container = container;
同
class AutofacModuleWebservice : Module { protected override void Load(ContainerBuilder builder) { builder.Register<Ajax>(); builder.Register<MapWebService>().ContainerScoped(); } }
在我的web.config我有
<services> <service name="Generic.Frontend.Web.Ajax"> <endpoint address="http://mysite.com/ajax.svc/" binding="webHttpBinding" contract="Generic.Frontend.Web.Ajax" /> </service> </services>
.
该服务已经正常工作,但是我无法获取Autofac位(读取:创建/注入)工作.有任何想法吗?
System.InvalidOperationException: 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.
干杯,奥利弗