I'm using an IServiceCollection
to create a list of required services for my objects. Now I want to instantiate an object and have the DI container resolve the dependencies for that object
Example
// In my services config.
services
.AddTransient<IMyService, MyServiceImpl>();
// the object I want to create.
class SomeObject
{
public SomeObject(IMyService service)
{
...
}
}
How to I get the DI container to create an object of type SomeObject
, with the dependecies injected? (presumably this is what it does for controllers?)
Note: I do not want to store SomeObject
in the services collection, I just want to be able to do something like this...
SomeObject obj = startup.ServiceProvider.Resolve<SomeObject>();
... Rationale: I don't have to add all of my controllers to the service container, so I don't see why I would have to add SomeObject
to it either!?
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
The recommended way to implement DI is, you should use DI containers. If you compose an application without a DI CONTAINER, it is like a POOR MAN'S DI . If you want to implement DI within your ASP.NET MVC application using a DI container, please do refer to Dependency Injection in ASP.NET MVC using Unity IoC Container.
ASP.NET Core contains a built-in dependency injection mechanism. In the Startup. cs file, there is a method called ConfigureServices which registers all application services in the IServiceCollection parameter. The collection is managed by the Microsoft.
What is DI Container. A DI Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on the request and injects them when required. DI Container helps us to manage dependencies within the application in a simple and easy way.
As stated in the comments to the marked answer, you can use ActivatorUtilities.CreateInstance
method. This functionality already exists in .NET Core (since version 1.0, I believe).
See: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.activatorutilities.createinstance
It's a little rough, but this works
public static class ServiceProviderExtensions
{
public static TResult CreateInstance<TResult>(this IServiceProvider provider) where TResult : class
{
ConstructorInfo constructor = typeof(TResult).GetConstructors()[0];
if(constructor != null)
{
object[] args = constructor
.GetParameters()
.Select(o => o.ParameterType)
.Select(o => provider.GetService(o))
.ToArray();
return Activator.CreateInstance(typeof(TResult), args) as TResult;
}
return null;
}
}
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