Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating objects with .NET Core's DI container

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!?

like image 653
Matthew Layton Avatar asked Oct 30 '16 22:10

Matthew Layton


People also ask

How does DI work in .NET Core?

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.

How do you implement DI?

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.

What is IoC container in .NET Core?

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 a DI container C#?

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.


2 Answers

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

like image 146
kiripk Avatar answered Sep 19 '22 03:09

kiripk


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;
        }
    }
like image 32
Matthew Layton Avatar answered Sep 21 '22 03:09

Matthew Layton