Reputation: 6625
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://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options
Upvotes: 4
Views: 1448
Reputation: 11470
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));
Upvotes: 5