2011-10-13 95 views
1

Wcf有很多依賴注入的例子,但其中很多都處理4.0之前的Wcf版本。我有一個用Wcf 4 Rest構建的應用程序,沒有.svc文件,基本上看起來像這樣。WCF Rest 4依賴注入

public class RestService : IRestService 
{ 
    IUserRepository _userRepo; 

    public RestService(IUserRepository repo) 
    { 
     _repo = repo; 
    } 
    public UserModel GetUser(int id) 
    { 
     return _repo.GetUserById(id); 
    } 
} 

public interface IRestService 
{ 
     [OperationContract] 
     [WebInvoke(Method = "GET", 
      ResponseFormat = WebMessageFormat.Json, 
      UriTemplate = "/User/{id}", 
      BodyStyle = WebMessageBodyStyle.Bare)] 
     UserModel GetUserById(int id); 
} 

就像我說的,沒有svc文件,整個九碼。只是這在global.asax文件

RouteTable.Routes.Add(new ServiceRoute("RestService", new WebServiceHostFactory(), typeof(RestService))); 

所以,我想要使用Castle Windsor注入UserRepository。

使用Castle Windsor 4.0設置服務的最佳方式是什麼?

+0

我認爲WCF Facility支持那不是嗎? –

+1

它確實如此,我已經在許多應用程序中使用過WCF工具,它相當方便地完成了這一工作。 –

回答

0

WCF中的依賴注入不是一件容易實現的事情。你基本上需要實現一個IServiceProvider,當需要創建一個新的服務實例時,它將被調用。然後,您可以使用Windsor或其他IoC工具來獲取存儲庫實例。

您可以在關於http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx的實例提供程序的帖子中找到此類IoC容器的示例。

+0

這是真的,或者至少除非你使用像Windsor的WCF工具那樣將WCF世界與容器橋接在一起。 –