Jam*_*ing 5 dependency-injection ninject asp.net-web-api hyprlinkr
我有一个MVC4 Web API项目,我利用Mark Seemann的Hyprlinkr组件生成Uris链接资源.(客户 - >地址例如).
我已经遵循了Mark的Web依赖注入指南(适用于Ninject),我无法理解将IResourceLinker注入控制器应该做些什么.
按照Mark的指南,我的IHttpControllerActivator.Create create方法如下所示:
IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = (IHttpController) _kernel.GetService(controllerType);
request.RegisterForDispose(new Release(() => _kernel.Release(controller)));
return controller;
}
Run Code Online (Sandbox Code Playgroud)
正是在这种方法中,Hyprlinkr自述文件建议创建RouteLinker.不幸的是我不知道如何在Ninject注册这个.
我不能像下面那样绑定,因为这会导致多个绑定:
_kernel.Bind<IResourceLinker>()
.ToMethod(context => new RouteLinker(request))
.InRequestScope();
Run Code Online (Sandbox Code Playgroud)
我有这样的重新绑定:
_kernel.Rebind<IResourceLinker>()
.ToMethod(context => new RouteLinker(request))
.InRequestScope();
Run Code Online (Sandbox Code Playgroud)
但我担心更改ninject绑定图对每个请求都可能是一件坏事.
实现这一目标的最佳方法是什么?
我在这里使用重新绑定:
IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
_kernel.Rebind<IResourceLinker>()
.ToMethod(context => new RouteLinker(request))
.InRequestScope();
var controller = (IHttpController) _kernel.GetService(controllerType);
request.RegisterForDispose(new Release(() => _kernel.Release(controller)));
return controller;
}
Run Code Online (Sandbox Code Playgroud)
每次请求都会调用IHttpControllerActivator.Create.其余的绑定是以标准方式进行的,标准意思是在使用Ninject.MVC3 nuget包生成的类中.
我的控制器看起来像这样:
public class CustomerController : ApiController
{
private readonly ICustomerService _customerService;
private readonly IResourceLinker _linker;
public CustomerController(ICustomerService customerService, IResourceLinker linker)
{
_customerService = customerService;
_linker = linker;
}
public CustomerModel GetCustomer(string id)
{
Customer customer = _customerService.GetCustomer(id);
if (customer == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return
new CustomerModel
{
UserName = customer.UserName,
Firstname = customer.Firstname,
DefaultAddress = _linker.GetUri<AddressController>(c => c.Get(customer.DefaultAddressId)),
};
}
}
Run Code Online (Sandbox Code Playgroud)
注册一个委托函数来为您提供链接器
_kernel.Bind<Func<HttpRequestMessage, IResourceLinker>>()
.ToMethod(context => (request) => new RouteLinker(request));
Run Code Online (Sandbox Code Playgroud)
注入代表
readonly Func<HttpRequestMessage, IResourceLinker> _getResourceLinker;
public controller(Func<HttpRequestMessage, IResourceLinker> getResourceLinker) {
_getResourceLinker = getResourceLinker;
}
Run Code Online (Sandbox Code Playgroud)
用于您的行动
public async Task<Thingy> Get() {
var linker = _getResourceLinker(Request);
linker.GetUri( ... )
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
701 次 |
| 最近记录: |