7 Tricky Questions to Ask .NET Developer in a Job Interview

With answers.

Sasha Marfut
Level Up Coding
Published in
6 min readSep 5, 2021

--

Photo by Van Tay Media on Unsplash

For those interviewers who might want to extend their list of interview questions, or those interviewees who might want to become more confident before the next interview, or just all .NET developers looking to learn something new, I’ve prepared some interesting questions.

1. Can a singleton object depend on a scoped/per-request object?

Or, the question could be rephrased as “Will the following piece of code work?”:

public class Controller
{
public Controller(UserService userService) { }
}
public class UserService
{
public UserService(IUserRepository userRepository) { }
}
public class UserRepository : IUserRepository
{
}
//DI registration:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<UserService>();
services.AddScoped<IUserRepository, UserRepository>();
}

This code will compile, but developers will get an exception thrown by the dependency injection container at the runtime.

The code example demonstrates the problem called captive dependencies. The problem occurs when the higher-level service (UserService) has longer lifetime than the dependent lower-level service (IUserRepository).

There are two ways to solve the problem. The first is to reconfigure the object lifetimes so that higher-level services always have the same or shorter lifetime than their dependencies. For example, both UserService and UserRepository can have a scoped (per request) lifetime. Or UserService can have a transient lifetime while UserRepository has a scoped lifetime.

However, it can sometimes be difficult to simply change the lifetime scopes of an object in large codebases because this can have an undesirable impact on the behavior of the entire application.

A working way to resolve a dependency with a shorter lifetime without changing lifetime scopes is to use IServiceScopeFactory.

public class UserService
{
private readonly IServiceScopeFactory _scopeFactory;
public…

--

--