2014-05-20 34 views
0

我正在構建一個WCF REST服務並希望使用Autofac作爲DI容器。我想能夠調用服務類的參數化構造函數。下面是我的代碼:如何在WCF Rest中觸發Autofac構造函數注入?

[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public partial class QDService:IQDService 
{ 
    public QDService(IApplicationService appService) 
    { 
     this.appService = appService; 
    } 

    private readonly IApplicationService appService; 
} 
在Global.asax

然後,我設置的配置按照this chapter

private void RegisterRoutes() 
    { 
     var builder = new ContainerBuilder(); 
     builder.RegisterType<QDService>(); 
     builder.RegisterType<ApplicationService>().As<IApplicationService>(); 
     var container = builder.Build(); 
     AutofacHostFactory.Container = container; 

     var factory = new AutofacWebServiceHostFactory(); 

     RouteTable.Routes.Add(new ServiceRoute("QDService", factory, typeof(QDService))); 

    } 

下面是方法,我要打電話:

[WebInvoke(Method = "GET" 
    , ResponseFormat = WebMessageFormat.Xml 
    , BodyStyle = WebMessageBodyStyle.Bare 
    , UriTemplate = "/Test/{test}")] 
    public string Test(string test) 
    { 
     return "HelloWorld!"; 
    } 

我啓動項目後瀏覽到

http://localhost:1685/QDService/Test/1 

瀏覽器把我像一個例外:

The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service. 

,我用螢火蟲來跟蹤它,發現這個: enter image description here

我不知道是什麼原因造成這一點,但之後我刪除了參數的構造函數,對我來說都工作得很好。然後,我在網上進行了一次快速搜索,但什麼也沒得到。需要你的幫助,thx。

+0

我調試服務,它在構造函數中是否中斷,是從容器中解析的appService? –

+0

@Jon_Lindeheim每次刷新頁面時,調試點都沒有觸發,但拋出了像上面這樣的異常。 – CharlieShi

+0

我已經通過網絡檢查了exption,發現我的請求中可能有一些格式錯誤。但我詳細檢查了它,沒有發現任何東西,所以有線。 – CharlieShi

回答