如何在.net Core中注册IViewComponentDescriptorProvider

本文关键字:注册 IViewComponentDescriptorProvider Core net | 更新日期: 2023-09-27 18:09:48

我已经使用SimpleInjector以与这里相同的方式设置了依赖注入。不幸的是,在容器对象上调用RegisterMvcViewComponents会抛出一个异常:

type没有服务"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(IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T]提供者)SimpleInjector.SimpleInjectorAspNetCoreMvcIntegrationExtensions.RegisterMvcViewComponents(容器容器,IApplicationBuilder, applicationBuilder)ProjectX.Startup。InitializeContainer (IApplicationBuilder应用)

如何在.net Core中注册IViewComponentDescriptorProvider

更改以下行:

services.AddMvcCore();

:

services.AddMvc();

简单注入器的RegisterMvcViewComponent方法需要在ASP中注册IViewComponentDescriptorProvider抽象。. NET核心配置系统。扩展方法使用IViewComponentDescriptorProvider来查找需要注册的视图组件。但是,您正在调用的AddMvcCore()扩展方法不注册此IViewComponentDescriptorProvider,因为AddMvcCore方法仅注册一些基本功能;它省略了特定于视图的东西。另一方面,AddMvc()扩展方法初始化整个包,包括与视图相关的东西,如IViewComponentDescriptorProvider .

如果对视图组件不感兴趣,也可以省略对RegisterMvcViewComponents()的调用。