Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core add/register a class as self to the service collection

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?

like image 395
DarthVader Avatar asked Jan 03 '23 07:01

DarthVader


1 Answers

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.

like image 199
Nkosi Avatar answered Jan 09 '23 00:01

Nkosi