title: How to invoke View Component in a Asp.net Core Service Class?
body: <p>I need to invoke a view component in a service class (not a controller). My aim to render the view component as a string and then process the <code>HtmlString</code>.</p>
  
  <p>I can find help to render a view component in a controller where <code>ActionContext</code> is available but I cannot call my service from a controller. Any help please? I am happy to use Mock and default dependency injection.</p>
  
  <p>Currently, I am using mvc 6 beta 2. Here is the code of my class</p>
  
  <pre><code>public class MyClass
  {
      Microsoft.AspNet.Mvc.DefaultViewComponentHelper viewComponentHelper = null;
      Microsoft.AspNet.Mvc.Razor.RazorView razorView = null;
  
      public MyClass(IViewComponentSelector selector, IViewComponentInvokerFactory factory,
          IRazorPageFactory razorPageFactory, IRazorViewEngine razorViewEngine, IRazorPageActivator pageActivator,
          IViewStartProvider viewStartProvider)
      {
          viewComponentHelper = new DefaultViewComponentHelper(selector, factory);
          razorView = new RazorView(razorViewEngine, pageActivator, viewStartProvider, null, true);
      }
  
      public void MyAction
      {
  
          var view = new Mock&lt;IView&gt;().Object;    
  
          var actionContext = new ActionContext(new RouteContext(new DefaultHttpContext()), new ActionDescriptor());
          var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
          var viewContext = new ViewContext(actionContext, view, viewData, TextWriter.Null);
  
          viewComponentHelper.Contextualize(viewContext);
          var result = viewComponentHelper.Invoke("MyView").ToString();
      }
  }
  </code></pre>
  
  <p>I am getting following exception</p>
  
  <pre><code>   at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
     at Microsoft.AspNet.Mvc.DefaultViewComponentActivator.&lt;&gt;c__DisplayClass6.&lt;CreateActivateInfo&gt;b__7(ViewContext viewContext)
     at Microsoft.AspNet.Mvc.PropertyActivator`1.Activate(Object view, TContext context)
     at Microsoft.AspNet.Mvc.DefaultViewComponentActivator.Activate(Object viewComponent, ViewContext context)
     at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.CreateComponent(ViewContext context)
     at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.InvokeSyncCore(MethodInfo method, ViewContext context)
     at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.Invoke(ViewComponentContext context)
     at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.InvokeCore(TextWriter writer, Type componentType, Object[] arguments)
     at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.Invoke(Type componentType, Object[] args)
     at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.Invoke(String name, Object[] args)
  </code></pre>