Dependency Injection of Value Types
I am creating an Azure Service Fabric service and relying on the native .NET framework for dependency injection through constructors. The problem is: one of the constructors has as parameter a value type (specifically System.TimeSpan). How should/can I register such type with the dependency injection framework?
To clarify: I am trying to follow the examples shown here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options
If possible, consider adding an interface like IDurationProvider
, that has a property of type TimeSpan
and register a type that implements it instead. This clarifies the developer & usage intent.
If you decide you really need this, this will work:
services.AddTransient(typeof(TimeSpan), _=> TimeSpan.FromSeconds(1D));
var serviceProvider = services.BuildServiceProvider();
var timespan = (TimeSpan)serviceProvider.GetRequiredService(typeof(TimeSpan));
链接地址: http://www.djcxy.com/p/82102.html
下一篇: 值类型的依赖注入