2016-10-02 34 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

相關問題