我是RESTful服務的新手,在一段時間內沒有必要使用IoC新建一個堆棧,所以這給了我一個溫和的中風。在.NET REST風格的應用程序中使用Ninject?
我有一個WCF服務,它看起來像這樣(簡化):
public interface IESIID
{
[OperationContract]
[WebGet(UriTemplate = "/{guid}/{id}", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
Message LookupESIID(string guid, string id);
}
public class ESIID : BaseREST<ESI>, IESIID
{
private readonly ITXESIIDService _bllSvc;
public ESIID(ITXESIIDService svc)
{
_bllSvc = svc;
}
public Message LookupESIID(string guid, string id)
{
return GetById(guid, id);
}
private Message GetById(string guid, string id)
{
apiAuthentication = new APIKeyAuthentication();
if (!apiAuthentication.IsValidAPIKey(guid))
return APIError();
//_bllSvc = new TXESIIDService(); <--- WANTING TO AVOID THIS!!!!
var results = _bllSvc.SelectByID(id);
return results.Count == 0 ? NoResults() : CreateMessage(results);
}
}
精細,這是非常簡單的。我添加了一個構造函數參數,因爲調用了BLL TXESIIDService方法。
所以,現在,我已經改變了我的Ninject全局文件現在看起來是這樣的:
public class Global : NinjectWcfApplication
{
protected override void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
protected override IKernel CreateKernel()
{
return new StandardKernel(new RestServiceModel());
}
private static void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("ESIID", new NinjectServiceHostFactory(), typeof(ESIID)));
}
}
,並還增加了我的模塊:
public class RestServiceModel : NinjectModule
{
public override void Load()
{
Bind<ITXESIIDService>().To<TXESIIDService>();
Bind<IDoNotSolicitService>().To<DoNotSolicitService>();
}
}
以及故障排除我通過添加自己NinjectServiceHostFactory
public class NinjectServiceHostFactory : WebServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var serviceTypeParameter = new ConstructorArgument("serviceType", serviceType);
var baseAddressesParameter = new ConstructorArgument("baseAddresses", baseAddresses);
return KernelContainer.Kernel.Get<NinjectServiceHost>(serviceTypeParameter, baseAddressesParameter);
}
}
當我運行這個在我得到一個錯誤,行:
return KernelContainer.Kernel.Get<NinjectServiceHost>(serviceTypeParameter, baseAddressesParameter);
不能爲空。
顯然我在這裏失去了一些東西,但我無法弄清楚什麼。在這一點上,我嘗試了各種各樣的東西,並且我看到的大多數例子都是針對WCF服務的,而我設法找到的REST服務例子對於那些熟悉的W/Ninject或IoC常客來說只是有點過分。
此外,在我的業務和數據層(使用實體框架)中,我也希望在那裏實現Ninject,最好是將層單獨連接起來,還是可以一次性完成點?
謝謝。
UPDATE 1 我糾正了綁定問題,但這仍然炸彈在我身上。我正在使用Ninject.Extensions.Wcf,它正在轟炸尋找NinjectWcfApplication.cs文件,這似乎並不正確。我使用NuGet爲Ninject包含一個軟件包,這可能是版本問題嗎?
上下文的背景,但我不會建議你的REST API使用WCF REST。那個項目已經死了。 –