SledgeHammer
SledgeHammer

Reputation: 7680

.Net Core How to new up a class using DI services?

Is there a way to new up an arbitrary class by type (i.e. Activator.CreateInstance(myType) and have the .Net DI engine inject the dependencies for that type? I don't want to register instances of myType and myType can be any random type. I just want to be able to handle cases like:

myType(IServiceProvider serviceProvider)

and have the DI inject the dependencies as expected. Doesn't happen through Activator obviously.

Upvotes: 0

Views: 539

Answers (2)

SymboLinker
SymboLinker

Reputation: 1189

Have look at IGet to use the functionality of ActivatorUtilities.CreateInstance in (maybe) better readable way.

At startup of your app, add:

serviceCollection.AddIGet();

Then get IGet i via dependency injection and use it like this:

var myClass = i.Get<MyClass>();

All the dependencies in the constructor of MyClass have been injected into myClass. (Make sure that all those dependencies are available in the serviceCollection or remove some of the dependencies from the constructor.)

Upvotes: 0

Tobias Tengler
Tobias Tengler

Reputation: 7454

Activator.CreateInstance doesn't support this out of the box, since it isn't connected to .NET Core's Dependency Injection in any way.

You should probably use ActivatorUtilities.CreateInstance to instantiate your DI connected types.

Upvotes: 3

Related Questions