我需要在服务类(而不是控制器)中调用视图组件。我的目标是将视图组件呈现为字符串,然后处理HtmlString
。
我可以找到帮助在ActionContext
可用的控制器中呈现视图组件,但我无法从控制器调用我的服务。有什么帮助吗?我很高兴使用Mock和默认依赖注入。
目前,我正在使用mvc 6 beta 2.这是我班级的代码
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<IView>().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();
}
}
我遇到了异常
at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.AspNet.Mvc.DefaultViewComponentActivator.<>c__DisplayClass6.<CreateActivateInfo>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)
答案 0 :(得分:1)
在启动文件的ConfigureServices部分中,您需要注册您的服务,即:
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
//services.AddMvc();
services.AddTransient...
}