2016-10-02 128 views
0

我已经使用SimpleInjector按照与here相同的方式设置了我的依赖注入。不幸的是,容器调用对象的RegisterMvcViewComponents抛出异常:如何在.NET Core中注册IViewComponentDescriptorProvider?

为 型无此项服务“Microsoft.AspNetCore.Mvc.ViewComponents.IViewComponentDescriptorProvider” 已注册。

容器是否有注册提供者的相应方法?还是应该以其他方式完成?

的代码:

public class Startup 
{ 
    private Container _container = new Container(); 

    public void ConfigureServices(IServiceCollection services) 
    { 
     services.InitializeTestData(); 

     services.AddMvcCore(); 

     services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(_container)); 
     services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(_container));   
    } 

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     app.UseSimpleInjectorAspNetRequestScoping(_container); 
     _container.Options.DefaultScopedLifestyle = new AspNetRequestLifestyle(); 
     InitializeContainer(app); 
     _container.Verify(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "Default", 
       template: "{controller=Home}/{action=Index}/{id?}" 
      ); 
     }); 
    } 

    private void InitializeContainer(IApplicationBuilder app) 
    { 
     _container.RegisterMvcControllers(app); 
     _container.RegisterMvcViewComponents(app); 

     _container.Register<IDbContext>(() => new DbContext("GuitarProject")); 
     _container.Register<IJournalEntryRepository, JournalEntryRepository>(); 
    } 
} 

堆栈跟踪(异常的类型是InvalidOperationException):

在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(的IServiceProvider 提供商类型的serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider provider)at SimpleInjector.SimpleInjectorAspNetCoreMvcIntegrationExtensions.RegisterMvcViewComponents(容器 容器,IApplicationBuilder applicationBuilder)在 ProjectX.Startup.InitializeContainer(IApplicationBuilder应用)

+0

你可以发布完整的堆栈跟踪吗? – Steven

+0

@Steven堆栈跟踪添加。 – Kapol

回答

1

更改以下行:

services.AddMvcCore(); 

到:

services.AddMvc(); 

简易注射器的RegisterMvcViewComponent方法d需要在ASP.NET Core配置系统中注册IViewComponentDescriptorProvider抽象。扩展方法使用IViewComponentDescriptorProvider来找出它需要注册哪些视图组件。但是,您拨打的AddMvcCore()扩展方法不会注册此IViewComponentDescriptorProvider,因为AddMvcCore方法只注册一些基本功能;它省略了视图特定的东西。另一方面,AddMvc()扩展方法,初始化整个包,包括视图相关的东西,如IViewComponentDescriptorProvider

如果您对视图组件不感兴趣,也可以省略致电RegisterMvcViewComponents()的电话。

+0

您的解决方案解决了问题。我今天刚开始学习.NET Core,所以当我安装MVC Core包而不是我需要的时候,我并不知道自己在做什么:-) – Kapol

+0

@Kapol我刚刚对集成包进行了改进。下一个版本将会引发一个messahe异常,这将更好地解释问题以及如何解决这个问题。 – Steven