sheru
sheru
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using WebApiBusiness.Abstraction;
using WebApiDomain.Shared;

namespace WebApiController.Controllers;

[ApiController]
[EnableCors("Policy1")]
[Route("api/v1/[controller]s")]
public class CrudController<T, TReadDto, TCreateDto, TUpdateDto> : ControllerBase
{
private readonly IBaseService<T, TReadDto, TCreateDto, TUpdateDto> _baseService;

public CrudController(IBaseService<T, TReadDto, TCreateDto, TUpdateDto> baseService)
{
_baseService = baseService;
}

[HttpGet]
public virtual async Task<ActionResult<IEnumerable<TReadDto>>> GetAll(
[FromQuery] QueryOptions queryOptions
)
{
return Ok(await _baseService.GetAll(queryOptions));
}

[HttpGet("{id:Guid}")]
public virtual async Task<ActionResult<TReadDto>> GetOneById([FromRoute] Guid id)
{
return Ok(await _baseService.GetOneById(id));
}

[HttpPost]
public virtual async Task<ActionResult<TReadDto>> CreateOne([FromBody] TCreateDto dto)
{
var createdObject = await _baseService.CreateOne(dto);
return CreatedAtAction(nameof(CreateOne), createdObject);
}

[HttpPatch("{id:Guid}")]
public virtual async Task<ActionResult<TReadDto>> UpdateOneById(
[FromRoute] Guid id,
[FromForm] TUpdateDto update
)
{
var updatedObject = await _baseService.UpdateOneById(id, update);
return Ok(updatedObject);
}

[HttpDelete("{id}")]
public virtual async Task<ActionResult<bool>> DeleteOneById([FromRoute] Guid id)
{
var deletedObject = await _baseService.DeleteOneById(id);
return Ok(deletedObject);
}
}
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using WebApiBusiness.Abstraction;
using WebApiDomain.Shared;

namespace WebApiController.Controllers;

[ApiController]
[EnableCors("Policy1")]
[Route("api/v1/[controller]s")]
public class CrudController<T, TReadDto, TCreateDto, TUpdateDto> : ControllerBase
{
private readonly IBaseService<T, TReadDto, TCreateDto, TUpdateDto> _baseService;

public CrudController(IBaseService<T, TReadDto, TCreateDto, TUpdateDto> baseService)
{
_baseService = baseService;
}

[HttpGet]
public virtual async Task<ActionResult<IEnumerable<TReadDto>>> GetAll(
[FromQuery] QueryOptions queryOptions
)
{
return Ok(await _baseService.GetAll(queryOptions));
}

[HttpGet("{id:Guid}")]
public virtual async Task<ActionResult<TReadDto>> GetOneById([FromRoute] Guid id)
{
return Ok(await _baseService.GetOneById(id));
}

[HttpPost]
public virtual async Task<ActionResult<TReadDto>> CreateOne([FromBody] TCreateDto dto)
{
var createdObject = await _baseService.CreateOne(dto);
return CreatedAtAction(nameof(CreateOne), createdObject);
}

[HttpPatch("{id:Guid}")]
public virtual async Task<ActionResult<TReadDto>> UpdateOneById(
[FromRoute] Guid id,
[FromForm] TUpdateDto update
)
{
var updatedObject = await _baseService.UpdateOneById(id, update);
return Ok(updatedObject);
}

[HttpDelete("{id}")]
public virtual async Task<ActionResult<bool>> DeleteOneById([FromRoute] Guid id)
{
var deletedObject = await _baseService.DeleteOneById(id);
return Ok(deletedObject);
}
}
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
thanks, will do
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
thank you so much for your help!!!
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
so I will leave it alone for now ...
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
yeah i don't know enough to do it otherwise right now, and I still need to do my front end (hello react my old friend)
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
and data source referring to var dataSource = npgsqlBuilder.Build();
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
Haha you're absolutely right, will change it to that. Also I solved it!... by adding this line dataSource.Dispose();
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
I am wondering if there's something wrong with how I used HTTP Context since it's mentioned in the error at the very bottom... Atlhough I don't really understand what it's saying. I only used HTTP Context here
public class OrderController : CrudController<Order, OrderReadDto, OrderCreateDto, OrderUpdateDto>
{
private readonly IOrderService _orderService;

public OrderController(IOrderService orderService)
: base(orderService)
{
_orderService = orderService;
}

public override async Task<ActionResult<OrderReadDto>> CreateOne([FromBody] OrderCreateDto dto)
{
var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);

if (userIdClaim == null)
{
return StatusCode(400, dto);
}

var userId = userIdClaim.Value;
if (!Guid.TryParse(userId, out Guid newId))
{
return StatusCode(400, dto);
}

var dtoWithId = await _orderService.CreateOrderAndOrderProducts(dto, newId);

return Ok(dtoWithId);
}
}
public class OrderController : CrudController<Order, OrderReadDto, OrderCreateDto, OrderUpdateDto>
{
private readonly IOrderService _orderService;

public OrderController(IOrderService orderService)
: base(orderService)
{
_orderService = orderService;
}

public override async Task<ActionResult<OrderReadDto>> CreateOne([FromBody] OrderCreateDto dto)
{
var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);

if (userIdClaim == null)
{
return StatusCode(400, dto);
}

var userId = userIdClaim.Value;
if (!Guid.TryParse(userId, out Guid newId))
{
return StatusCode(400, dto);
}

var dtoWithId = await _orderService.CreateOrderAndOrderProducts(dto, newId);

return Ok(dtoWithId);
}
}
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
Ah I see, thank you for the info.
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
also I keep seeing Startup.cs but for some reasons our instructor doesn't use it at all
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
services as in from the IServicCollection?
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
I'm not sure if it's necessary to do this line builder.Services.AddSingleton(npgsqlBuilder); but I read somewhere that maybe this needs to be a singleton and shouldn't have an instance created every time. anyway the problem still persists
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
I did as you recommended (at least from what I understood) and moved things to program.cs.
var builder = WebApplication.CreateBuilder(args);
var timeStampInterceptor = new TimeStampInterceptor();
var npgsqlBuilder = new NpgsqlDataSourceBuilder(
builder.Configuration.GetConnectionString("Default")
);
builder.Services.AddSingleton(npgsqlBuilder);
builder.Services.AddSingleton(timeStampInterceptor);

...

builder.Services.AddDbContext<DatabaseContext>(
options =>
{
options.AddInterceptors(timeStampInterceptor);
options.UseNpgsql(npgsqlBuilder.Build()).UseSnakeCaseNamingConvention();
npgsqlBuilder.MapEnum<Role>();
npgsqlBuilder.MapEnum<OrderStatus>();
},
ServiceLifetime.Scoped
);
var builder = WebApplication.CreateBuilder(args);
var timeStampInterceptor = new TimeStampInterceptor();
var npgsqlBuilder = new NpgsqlDataSourceBuilder(
builder.Configuration.GetConnectionString("Default")
);
builder.Services.AddSingleton(npgsqlBuilder);
builder.Services.AddSingleton(timeStampInterceptor);

...

builder.Services.AddDbContext<DatabaseContext>(
options =>
{
options.AddInterceptors(timeStampInterceptor);
options.UseNpgsql(npgsqlBuilder.Build()).UseSnakeCaseNamingConvention();
npgsqlBuilder.MapEnum<Role>();
npgsqlBuilder.MapEnum<OrderStatus>();
},
ServiceLifetime.Scoped
);
and now dbcontext is as such:
public class DatabaseContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderProducts> OrderProducts { get; set; }
public DbSet<Image> Images { get; set; }

public DatabaseContext(DbContextOptions options)
: base(options) { }

static DatabaseContext()
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();
modelBuilder.HasPostgresEnum<Role>();
modelBuilder.HasPostgresEnum<OrderStatus>();
modelBuilder.Entity<OrderProducts>().HasKey("OrderId", "ProductId");
}
}
public class DatabaseContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderProducts> OrderProducts { get; set; }
public DbSet<Image> Images { get; set; }

public DatabaseContext(DbContextOptions options)
: base(options) { }

static DatabaseContext()
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();
modelBuilder.HasPostgresEnum<Role>();
modelBuilder.HasPostgresEnum<OrderStatus>();
modelBuilder.Entity<OrderProducts>().HasKey("OrderId", "ProductId");
}
}
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
I was taught that this is the way to go, using _config to get the default connection string in the appsettings.json. im not really sure how to feed it to dbcontext directly. I'm guessing using builder.services in program.cs? is it very significant to do it this way vs what you recommended?
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
yeah there is a constructor, here is the whole config. also i just learned this whole thing 2 weeks ago so please bear with me 🙂
public class DatabaseContext : DbContext
{
public readonly IConfiguration _config;
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderProducts> OrderProducts { get; set; }
public DbSet<Image> Images { get; set; }
private static readonly TimeStampInterceptor Interceptor = new TimeStampInterceptor(); // Create a static instance

public DatabaseContext(DbContextOptions options, IConfiguration config)
: base(options)
{
_config = config;
}

static DatabaseContext()
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new NpgsqlDataSourceBuilder(_config.GetConnectionString("Default"));
optionsBuilder.AddInterceptors(Interceptor);
optionsBuilder.UseNpgsql(builder.Build()).UseSnakeCaseNamingConvention();
builder.MapEnum<Role>();
builder.MapEnum<OrderStatus>();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();
modelBuilder.HasPostgresEnum<Role>();
modelBuilder.HasPostgresEnum<OrderStatus>();
modelBuilder.Entity<OrderProducts>().HasKey("OrderId", "ProductId");
}
}
public class DatabaseContext : DbContext
{
public readonly IConfiguration _config;
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderProducts> OrderProducts { get; set; }
public DbSet<Image> Images { get; set; }
private static readonly TimeStampInterceptor Interceptor = new TimeStampInterceptor(); // Create a static instance

public DatabaseContext(DbContextOptions options, IConfiguration config)
: base(options)
{
_config = config;
}

static DatabaseContext()
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new NpgsqlDataSourceBuilder(_config.GetConnectionString("Default"));
optionsBuilder.AddInterceptors(Interceptor);
optionsBuilder.UseNpgsql(builder.Build()).UseSnakeCaseNamingConvention();
builder.MapEnum<Role>();
builder.MapEnum<OrderStatus>();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();
modelBuilder.HasPostgresEnum<Role>();
modelBuilder.HasPostgresEnum<OrderStatus>();
modelBuilder.Entity<OrderProducts>().HasKey("OrderId", "ProductId");
}
}
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
fair 🙂 i was thinking along "look in service, maybe theres a x or y" but thanks anyway
47 replies
CC#
Created by sheru on 8/30/2023 in #help
❔ ✅ How to debug "More than twenty 'IServiceProvider' instances have been created ... "?
Hey, if i was unclear, i meant that in general, how do you go about solving this and where to look in general.
47 replies
CC#
Created by sheru on 8/29/2023 in #help
❔ Retrieving GUID from db with EF core returning 0s
but why?
60 replies
CC#
Created by sheru on 8/29/2023 in #help
❔ Retrieving GUID from db with EF core returning 0s
did new migration and db update and it works
60 replies
CC#
Created by sheru on 8/29/2023 in #help
❔ Retrieving GUID from db with EF core returning 0s
i just added step one
60 replies