Asp.Net Core Web Api - DI problem

Cenk 1,036 Reputation points
2022-12-20T13:25:48.383+00:00

Hi,

I have a problem with DI while upgrading from legacy asp.net web API to core. In my legacy code, I was using Unity as follows:

container.RegisterType<IGameServices, GameServices>().RegisterType<UnitOfWork>(new TransientLifetimeManager());  

Since Asp.net core web API supports DI as default, I think I don't need a third party DI framework. So I tried like this:

var builder = WebApplication.CreateBuilder(args);  
  
// Add services to the container.  
builder.Services.AddControllers();  
builder.Services.AddDbContext<GameApiDbContext>(  
    options => options.UseSqlServer("name=ConnectionStrings:GameApiDbContext"));  
builder.Services.AddTransient<IOyunPalasServices, OyunPalasServices>().AddTransient<UnitOfWork>();  
  
builder.Services.AddTransient<IUserValidate, UserValidate>();  
  
builder.Services.AddAutoMapper(typeof(MappingProfile).Assembly);  
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  
builder.Services.AddEndpointsApiExplorer();  
builder.Services.AddSwaggerGen();  
  
var app = builder.Build();  
  
// Configure the HTTP request pipeline.  
if (app.Environment.IsDevelopment())  
{  
    app.UseSwagger();  
    app.UseSwaggerUI();  
}  
  
app.UseHttpsRedirection();  
  
app.UseAuthorization();  
  
app.MapControllers();  
  
app.Run();  

But got this error:

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: OyunPalasGame.Services.IOyunPalasServices Lifetime: Transient ImplementationType: OyunPalasGame.Services.OyunPalasServices': Unable to resolve service for type 'OyunPalasGame.Data.GenericGameRepository1[OyunPalasGame.Entity.GameRequest]' while attempting to activate 'OyunPalasGame.Data.UnitOfWork'.) (Error while validating the service descriptor 'ServiceType: OyunPalasGame.Data.UnitOfWork Lifetime: Transient ImplementationType: OyunPalasGame.Data.UnitOfWork': Unable to resolve service for type 'OyunPalasGame.Data.GenericGameRepository1[OyunPalasGame.Entity.GameRequest]' while attempting to activate 'OyunPalasGame.Data.UnitOfWork'.) (Error while validating the service descriptor 'ServiceType: OyunPalasGame.Services.IUserValidate Lifetime: Transient ImplementationType: OyunPalasGame.Services.UserValidate': Unable to resolve service for type 'OyunPalasGame.Data.GenericGameRepository`1[OyunPalasGame.Entity.GameRequest]' while attempting to activate 'OyunPalasGame.Data.UnitOfWork'.)

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.