Victor Santos Victor Santos - 2 months ago 48
C# Question

ASP.NET Core View Injection problems

Has anyone tried to use the new View Injection from ASP.NET Core?
I'm trying to use straight forward as described on the documentation ( but no success at all.

The unique diference from my implementation and the documentation is that I'm using AutoFac for DI.
When I try to use the injection on my view I get an exception that my Service has not been registered.

@inject Domain.Service.LevelService LevelService

Error Message:

ComponentNotRegisteredException: The requested service 'Domain.Service.LevelService' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

Btw, the service is correctly registered and can be accessed from the controller for example.

Edit to include Startup:

public IServiceProvider ConfigureServices(IServiceCollection services)
// Add framework services.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

return new AutofacServiceProvider(DependencyInjection.RegisterServices(services));

Code of the method RegisterServices:

public static IContainer RegisterServices(IServiceCollection services)
// Create the container builder.
var builder = new ContainerBuilder();

var assembly = Assembly.GetExecutingAssembly();

.Where(x => x.IsSubclassOf(typeof(ServiceInjectionModule)))
.ForEach(x =>
var t = (ServiceInjectionModule)Activator.CreateInstance(x, new object[] { true });

// Add automapper configurations
var mapperConfiguration = AutoMapperConfig.Configure();
var mapper = mapperConfiguration.CreateMapper();

// Populate default services

return builder.Build();


OK, I solved the problem. Well, I didn't paid attention and seems that no one too :p.

The problem is that I'm trying to inject an instance and not an interface. Just changed the implementation and everything started working.

Final code:

@inject Domain.Service.Interfaces.ILevelService LevelService