78

I'm having this problem: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered. In asp.net core 1.0, it seems that when the action try to render the view i have that exception.

I've searched a lot but I dont found a solution to this, if somebody can help me to figure out what's happening and how can I fix it, i will appreciate it.

My code bellow:

My project.json file

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"

    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

My Startup.cs file

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OdeToFood.Services;

namespace OdeToFood
{
    public class Startup
    {
        public IConfiguration configuration { get; set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
            services.AddMvcCore();
            services.AddSingleton(provider => configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

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

            app.UseFileServer();

            app.UseMvc(ConfigureRoutes);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
        }
    }
}
3
  • Is it happening to a specific page ? What are you trying to do in that page ? Also when you comment out the registration of IRestaurantData, were you able to replicate the issue ? Commented Aug 1, 2016 at 23:39
  • @Shyju, thanks for the replay, it's happening just when I try to call the View() method for display a view in any action of my homeController, always even I dont overload the method It always throw the exception, also when I comment the IRestaurantData registration service the issue still happening, is so weird this problem :( because it seems like I'm missing some namespace orsomething but the vs don't show me anything wrong in the code Commented Aug 2, 2016 at 2:40
  • @Shyju this are the namespace i'm using: using Microsoft.AspNetCore.Mvc; using OdeToFood.ViewModels; using OdeToFood.Services; using OdeToFood.Entities; Commented Aug 2, 2016 at 2:45

14 Answers 14

83

Solution: Use AddMvc() instead of AddMvcCore() in Startup.cs and it will work.

Please see this issue for further information about why:

For most users there will be no change, and you should continue to use AddMvc() and UseMvc(...) in your startup code.

For the truly brave, there's now a configuration experience where you can start with a minimal MVC pipeline and add features to get a customized framework.

https://github.com/aspnet/Mvc/issues/2872

You might also have to add a reference toMicrosoft.AspNetCore.Mvc.ViewFeature in project.json

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.ViewFeatures/

Sign up to request clarification or add additional context in comments.

Comments

71

If you're using 2.x then use services.AddMvcCore().AddRazorViewEngine(); in your ConfigureServices

Also remember to add .AddAuthorization() if you're using Authorize attribute, otherwise it won't work.

Update: for 3.1 onwards use services.AddControllersWithViews();

1 Comment

Thank your for you answer. For our Project it was this one: services.AddControllersWithViews(); Thanks a lot!
31

I know this is an old post but it was my top Google result when running into this after migrating an MVC project to .NET Core 3.0. Making my Startup.cs look like this fixed it for me:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Comments

13

In .NET Core 3.1, I had to add the following:

services.AddRazorPages();

in ConfigureServices()

And the below in Configure() in Startup.cs

app.UseEndpoints(endpoints =>
{
     endpoints.MapRazorPages();
}

1 Comment

keyword is NET Core 3.1, these two lines helped me right away
5

In 2022 with .NET 6.0,

Add this line to Program.cs

var builder = WebApplication.CreateBuilder(args); //After this line...
builder.Services.AddRazorPages(); //<--This line

Comments

3

For Net Core (NET 6.0 or above using VS 2022) this error may happen when trying to consume views. To avoid this issue don't forget when configuring Program.cs to use AddControllersWithViews instead of AddControllers

An Example of the fix:

using Microsoft.EntityFrameworkCore;
using WebApp.Net.Core.Api.EF.Core.Angular.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var configurationService =  builder.Services.BuildServiceProvider().GetService<IConfiguration>();
builder.Services.AddDbContext<AppDbContext1>(options => options.UseSqlServer(configurationService.GetConnectionString("appSetttingsCon1")));
//builder.Services.AddControllers();//this will trigger the error when consuming views
builder.Services.AddControllersWithViews();//this fixes the issue

Comments

2

For .NET Core 2.0, in ConfigureServices, use :

services.AddNodeServices();

Comments

2

Solution: Use services.AddMvcCore(options => options.EnableEndpointRouting = false).AddRazorViewEngine(); in Startup.cs and it will work.

This code is tested for asp.net core 3.1 (MVC)

Comments

1

Right now i has same problem, I was using AddMcvCore like you. I found error self descriptive, as an assumption I added AddControllersWithViews service to ConfigureServices function and it fixed problem for me. (I still use AddMvcCore as well.)

    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddControllers();
        services.AddControllersWithViews();
        services.AddMvcCore();
        //...
    }    

Comments

0

Just add following code and it should work:

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                    .AddViews();

        }

Comments

0

For those that get this issue during .NetCore 1.X -> 2.0 upgrade, update both your Program.cs and Startup.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

public class Startup
{
// The appsettings.json settings that get passed in as Configuration depends on 
// project properties->Debug-->Enviroment Variables-->ASPNETCORE_ENVIRONMENT
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    // no change to this method leave yours how it is
    }
}

Comments

0

This one works for my case :

services.AddMvcCore()
.AddApiExplorer();

Comments

0

You use this in startup.cs

services.AddSingleton<PartialViewResultExecutor>();

1 Comment

This just led me down a rabbit hole. I had to register all these other interfaces as well, and I couldn't find an implementation for the top one: cs .AddScoped<ITempDataProvider, >() .AddSingleton<ITempDataDictionaryFactory, TempDataDictionaryFactory>() .AddSingleton<ICompositeViewEngine, CompositeViewEngine>() .AddSingleton<PartialViewResultExecutor>()
0

I'm currently using VS 2022 and .NET 6.

The following line was giving me the error as described, and I incorrectly tried removing the entire line, but that did not work. The offending line:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

It was as simple as removing the SetCompatibilityVersion part:

services.AddMvc()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.