所以我一直在玩WCF Web API的最新版本,并决定我想用它来实现Ninject。
基于我读过的内容,我需要实现IResourceFactory接口,该接口需要以下方法:
public object GetInstance(System.Type serviceType,
System.ServiceModel.InstanceContext instanceContext,
System.Net.Http.HttpRequestMessage request);
public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext,
object service);
所以我把鸡抓了下来:
public class NinjectResourceFactory : IResourceFactory
{
private readonly IKernel _kernel;
public NinjectResourceFactory()
{
var modules = new INinjectModule[]
{
new ServiceDIModule(), //Service Layer Module
new RepositoryDIModule(), //Repo Layer Module
new DataServiceDIModule()
};
_kernel = new StandardKernel(modules);
}
#region IResourceFactory Members
public object GetInstance(Type serviceType,
InstanceContext instanceContext,
HttpRequestMessage request)
{
return Resolve(serviceType);
}
public void ReleaseInstance(InstanceContext instanceContext, object service)
{
throw new NotImplementedException();
}
#endregion
private object Resolve(Type type)
{
return _kernel.Get(type);
}
//private T Resolve<T>()
//{
// return _kernel.Get<T>();
//}
//private T Resolve<T>(string name)
//{
// return _kernel.Get<T>(metaData => metaData.Has(name));
// return _kernel.Get<T>().Equals(With.Parameters.
// ContextVariable("name", name));
//}
}
并用
连接var configuration = HttpHostConfiguration.Create().SetResourceFactory(new NinjectResourceFactory());
RouteTable.Routes.MapServiceRoute<StateProvinceResource>("States", configuration);
令人惊讶的是,这似乎有效。我创建的第一个用于提供状态/省份列表的资源方法使用HTTP 200 OK生成输出。
所以,问题。是否有清洁编写这个工厂的方式?我真的很喜欢它,感觉不对劲。我觉得我错过了一些明显盯着我的东西。我在新的Resolve方法中做的黑客感觉特别脏,所以我想我会利用那些经验丰富的人来收紧它。有没有其他人使用WCF Web API实现Ninject并实现了更清洁的解决方案?
感谢您的任何意见!
答案 0 :(得分:0)
您可以通过从应用程序范围传入内核来实现它。
public class NinjectResourceFactory : IResourceFactory
{
private readonly IKernel _kernel;
public NinjectResourceFactory(IKernel kernel)
{
_kernel = kernel;
}
public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
{
return _kernel.Get(serviceType);
}
public void ReleaseInstance(InstanceContext instanceContext, object service)
{
// no op
}
}