c# - 值类型的依赖注入(inject)

标签 c# azure dependency-injection microservices azure-service-fabric

我正在创建一个 Azure Service Fabric 服务,并依靠 native .NET 框架通过构造函数进行依赖项注入(inject)。问题是:其中一个构造函数将值类型(特别是 System.TimeSpan)作为参数。我应该/如何使用依赖注入(inject)框架注册这种类型?

澄清一下:我正在尝试遵循此处显示的示例:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options

最佳答案

如果可能,请考虑添加一个类似 IDurationProvider 的接口(interface),该接口(interface)具有 TimeSpan 类型的属性,并注册一个实现该接口(interface)的类型。这澄清了开发人员和使用意图。

如果您确定确实需要这个,那么这会起作用:

 services.AddTransient(typeof(TimeSpan), _=> TimeSpan.FromSeconds(1D));
 var serviceProvider = services.BuildServiceProvider();
 var timespan = (TimeSpan)serviceProvider.GetRequiredService(typeof(TimeSpan));

关于c# - 值类型的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48347363/

相关文章:

azure - 如何更改azure网站服务中的默认时区?

azure - 无法调用http ://localhost Azure Function from https://localhost node app

.net - Azure Functions 主机运行配置 - 运行所有函数

c# - c#.net 中 throw 和 throw ex 的区别

c# - 如何在不更改 C# 中特殊字符位置的情况下反转字符串数组

c# - 如何在请求结束时释放资源并在 ASP.NET 5/Core 中处理注入(inject)的服务?

asp.net-mvc - 在 ASP.NET MVC Controller 中注入(inject)依赖项的不同方法?

c# - 具有依赖注入(inject)设计的处理程序工厂

c# - MudBlazor 树达到 4 级时速度非常慢

c# - App_Code 中的 SignalR Hub 导致 "Two Hubs must not share the same name"错误