【发布时间】:2017-09-09 10:07:23
【问题描述】:
我正在使用 ninject 作为依赖解析器的 web api
场景:
我需要生成一个 pdf 格式的报告,其中包括报告数据和组织地址作为报告标题。
当前实施:
我有 2 个控制器,即 OrganisationController 和 ReportController。
- 组织控制器具有组织的 CRUD 操作。
- 报表控制器有 get 方法来获取基于报表的详细信息 ID。在这里它接受 application/json 和 application/pdf 作为 Accept 标题
- 对于 pdf,我创建了自定义 PDF Formater 并使用 MigraDoc 工具。
问题:
在创建 pdf 时,我访问标题的组织数据。 Pdf 生成正确,并且还包含组织数据。在我使用组织控制器 put 方法更新组织数据之后。当我再次创建报告时,它会显示旧的组织数据。
我的嫌疑人:
- Report1 构造函数只调用一次。所以组织逻辑不是 重新初始化。这可能是由于不正确的 dispose 或 ninject scope。
我的代码:
注入注册码:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IOrganisationDetailLogic>().To<OrganisationDetailLogic>();
kernel.Bind<IOrganisationDetailRepository>().To<OrganisationDetailRepository>();
kernel.Bind<IReport>().To<Report1>();
kernel.Bind<PdfMediaTypeFormatter>().ToSelf();
}
报告类:
public class Report1 : IReport
{
private readonly IOrganisationDetailLogic _organisationLogic;
public Report1(IOrganisationDetailLogic organisationLogic)
{
_organisationLogic = organisationLogic;
}
public async Task<MemoryStream> Create(object model)
{
MemoryStream stream = null;
Document document = new Document();
//Report Header
SetHeader(section);
//Report Data here
//Footer
SetFooter(section);
//Render as PDF
return stream;
}
private void SetHeader(Section section)
{
//Here we are getting organisation data
var organisationDetail = _organisationLogic.GetActiveOrganisations().First();
}
}
请在我错过的地方提供帮助。当我在 SetHeader 本身中启动 _organisationLogic 时,它的工作正常
更新: 我正在添加我的自定义格式化程序类。
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);
private readonly IReport _report;
public PdfMediaTypeFormatter(IReport report)
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));
MediaTypeMappings.Add(new UriPathExtensionMapping("pdf", new MediaTypeHeaderValue(mediaType)));
this._report = report;
}
public async override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var memoryStream = await _report.Create(value);
var bytes = memoryStream.ToArray();
await writeStream.WriteAsync(bytes, 0, bytes.Length);
}
//other methods skipped
}
我读到自定义格式化程序不支持构造函数注入,请建议
【问题讨论】:
标签: c# asp.net-web-api ninject-extensions