I am trying to add a class as self in to the container.
However, since the class is expecting some dependencies in the constructor, it is complaining with a syntax error.
services.TryAddSingleton<TimeoutPolicyHolder>(new TimeoutPolicyHolder());
How can I add this class as self?
Same in AutoFac would be:
builder.RegisterType<FooService>().AsSelf();
How do I get around this problem?
You can add the service itself to the service collection using the generic extension.
services.AddSingleton<TimeoutPolicyHolder>();
Or one of the available overloads.
The container will take care of initializing the service and injecting any dependencies.
If you want to create the instance manually you can use the factory delegate
services.TryAddSingleton<TimeoutPolicyHolder>(sp =>
new TimeoutPolicyHolder(sp.GetService<Dependency1>(),...)
);
It will have access to the service provider when invoked so that any dependencies that need to be resolved can be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With