How to create instance of a class and inject services?

FLCL picture FLCL · Jan 12, 2016 · Viewed 11.2k times · Source

New aspnet has in-build dependency injection: Startup class instance receives services, controllers, view components do. Is there any way for me to create object of my class and pass services using aspnet functionality? Something like:

WebApplicationClassesActivator.Create(typeof(MyClass))

where MyClass contains constructor receiving IHostingEnvironment instance, for example.

Real usage:

public class MyController : Controller
{
    private readonly IContext Context;
    public MyController(IContext context)
    {
        Context = context;
    }
    public IActionResult Index(string className)
    {            
        return View(WebApplicationClassesActivator.Create(Type.GetType(className)));
    }
}

Where classsName is name of classes like:

public class A
{
    public A(IContext context, IHostingEnvironment env)
    {
       ...
    }
}

Answer

FLCL picture FLCL · Jan 12, 2016

Assembly Microsoft.Extensions.DependencyInjection.Abstractions contains static class ActivatorUtilities which has what I need:

public static object CreateInstance(IServiceProvider provider, 
                                    Type instanceType, 
                                    params object[] parameters);

and I can create instance and inject services:

private readonly IServiceProvider Provider;

public HomeController(IServiceProvider provider)
{       
    Provider = provider;
}

public IActionResult Index()
{       
    var instance = ActivatorUtilities.CreateInstance(Provider, typeof(A));

    return View(instance);
}

public class A
{
    public A(IContext context)
    {

    }
}