Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create instance of a class and inject services?

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)
    {
       ...
    }
}
like image 652
FLCL Avatar asked Jan 12 '16 13:01

FLCL


1 Answers

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

    }
}
like image 166
FLCL Avatar answered Oct 08 '22 13:10

FLCL