C
C#7mo ago
Brady Kelly

ASP.NET Dependency Injection Fails to instantiate service

I'm trying to inject a service over which I have no control (hence no use of an interface) and determine why the DI container cannot instantiate the service. This code applies:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<Users>();
builder.Services.AddScoped<UsersRepository>();
...
class UsersRepository {
CTSCore.Security.Users Users;
public UsersRepository()
{
Users = new();
}
}
...
public class LoginEndpoint: Endpoint<LogonRequest, Results<Ok<LoginResponse>, UnauthorizedHttpResult>>
{
public UsersRepository? Repository { get; set; }
UsersRepository? _repository;
public LoginEndpoint(UsersRepository repository)
{
_repository = repository;
}
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<Users>();
builder.Services.AddScoped<UsersRepository>();
...
class UsersRepository {
CTSCore.Security.Users Users;
public UsersRepository()
{
Users = new();
}
}
...
public class LoginEndpoint: Endpoint<LogonRequest, Results<Ok<LoginResponse>, UnauthorizedHttpResult>>
{
public UsersRepository? Repository { get; set; }
UsersRepository? _repository;
public LoginEndpoint(UsersRepository repository)
{
_repository = repository;
}
}
UsersRepository doesn't get injected into LoginEndpoint when I rely on CTSCore.Security.Users being injected, but when I create in manually, the repo does get injected into the endpoint. I've tried using an Oakton environment check like this:
builder.Services.AddScoped<Users>();
...
public static void CheckServiceIsRegistered<T>(this IServiceCollection services)
{
services.CheckEnvironment($"Service {typeof(T).FullName} should be registered", s => s.GetRequiredService<T>());
}
builder.Services.AddScoped<Users>();
...
public static void CheckServiceIsRegistered<T>(this IServiceCollection services)
{
services.CheckEnvironment($"Service {typeof(T).FullName} should be registered", s => s.GetRequiredService<T>());
}
but this check fails when invoked. How can I determine why the container is not registering a CTSCore.Security.Users instance when I can easily do it myself?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server