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