0

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.

2
  • @TobiasTengler - you should probably post your comment as an answer since that's probably the best way to do this. Commented Jun 21, 2019 at 19:31
  • @TobiasTengler Yes sir! That was it. Been googling random terms all morning lol. Thanks. Commented Jun 21, 2019 at 19:34

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.