【发布时间】:2017-04-20 19:06:12
【问题描述】:
我在 webapi 中使用 ninject 作为依赖注入器。我所有的构造函数注入都对我的控制器工作正常。
我有自定义媒体类型格式化程序,当用户请求“应用程序/pdf”时,它会返回 pdf
这里我需要在创建 pdf 后更新数据。所以在这里我需要调用我的业务类来更新数据。
MyCustomFormatter 代码:
public class PdfMediaTypeFormatter : MediaTypeFormatter
{
private readonly string mediaType = "application/pdf";
Func<Type, bool> typeisIPdf = (type) => typeof(IPdf).IsAssignableFrom(type);
Func<Type, bool> typeisIPdfCollection = (type) => typeof(IEnumerable<IPdf>).
IsAssignableFrom(type);
public PdfMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));
MediaTypeMappings.Add(new UriPathExtensionMapping("pdf", new MediaTypeHeaderValue(mediaType)));
}
public override bool CanReadType(Type type)
{
return false;
}
public override bool CanWriteType(Type type)
{
return typeisIPdf(type) || typeisIPdfCollection(type);
}
public async override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var pdfData= new SamplePdf();
var memoryStream = report.Create(value);
var bytes = memoryStream.ToArray();
await writeStream.WriteAsync(bytes, 0, bytes.Length);
}
}
我的 SamplePdf 类代码:
public class SamplePdf
{
private readonly IBusinessLogic _logic;
public MemoryStream Create(object model)
{
//Pdf generation code
// here i need to call data update
//_logic.update(model);
}
}
我需要在我的商务舱中注入_logic 字段。我已经在下面的 ninject 配置中映射了相同的内容;
kernel.Bind<IBusinessLogic>().To<MyBusinessLogic>().InRequestScope();
如何将这个注入我的班级?
【问题讨论】:
-
是什么阻止您将其注入格式化程序?
-
格式化程序是无参数的。如果我在那里包含注入,我们将如何更改 webapi 配置中的代码。我的意思是自定义格式化程序注册码
标签: c# asp.net-web-api dependency-injection ninject