DEV Community

Cover image for [Part 3] If You Can Answer These Additional 7 Questions Correctly, You’re Decent at .NET
Sukhpinder Singh
Sukhpinder Singh

Posted on • Originally published at Medium

[Part 3] If You Can Answer These Additional 7 Questions Correctly, You’re Decent at .NET

Hello .NET Enthusiasts,

Welcome to Part 3 of our C# knowledge test challenge! Please go through Parts 1 and 2.
If You Can Answer These 7 Concepts Correctly, You’re Decent at .NET
If You Can Answer These 7 Questions Correctly, You’re a Decent Developer

The next set of questions will test your knowledge of advanced .NET concepts and practices.

1. Dependency Injection Lifetimes

Dependency injection is one of the methods for managing service lifetime. Understanding different service lifetimes is crucial to manage resources properly and help in good application performance.

1. What are various service lifetimes supported by ASP.NET Core

and how do each of them impact the behavior of services? Please provide examples for each.

Answer: ASP.NET Core supports three main service lifetimes:

  • Transient: These are created each time they are requested. Suitable for lightweight, stateless services.
    services.AddTransient<IMyTransientService, MyTransientService>();
Enter fullscreen mode Exit fullscreen mode
  • Scoped: It creates instances once per request, and it is an ideal choice for services that have to keep state during a request.
    services.AddScoped<IMyScopedService, MyScopedService>();
Enter fullscreen mode Exit fullscreen mode
  • Singleton: It involves a single creation and sharing through a lifetime. It’s ideal for services maintaining global states or is pretty expensive to create.
    services.AddSingleton<IMySingletonService, MySingletonService>();
Enter fullscreen mode Exit fullscreen mode

Choosing the right lifetime helps balance performance and resource management.

2. Task.WhenAll and Task.WhenAny

Question: How does Task.WhenAll differ from Task.WhenAny?

Answer:

  • Task.WhenAll Waits for all the tasks to be completed and returns a single task which is completed when all of the provided tasks have been completed.
    var tasks = new List<Task> {     
      FetchDataAsync1(),     
      FetchDataAsync2(),     
      FetchDataAsync3() 
    };  

    await Task.WhenAll(tasks);
Enter fullscreen mode Exit fullscreen mode
  • Task.WhenAny Returns a task that completes when any of the tasks within Task.WhenAny completes
    var tasks = new List<Task> {     
      FetchDataAsync1(),     
      FetchDataAsync2(),     
      FetchDataAsync3() 
    };  
    var completedTask = await Task.WhenAny(tasks);
Enter fullscreen mode Exit fullscreen mode

Use Task.WhenAll when you need to execute several tasks in parallel and then wait for all to finish. Use Task.WhenAny when you process the first completed task and often cancel the others.

3. Custom Model Binders in ASP.NET Core

Model binding in ASP.NET Core allows you to bind HTTP request data to action method parameters. Sometimes you may want to create a custom model binder because the default model binders have some limitations to solve your specific complex binding scenarios.

Question: How to integrate model binder in ASP.NET Core?

Answer: To create a custom model binder:

  1. Implement IModelBinder.

  2. Register the custom model binder in Startup.cs.

Example:

    public class CustomModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue("customValue").FirstOrDefault();
            bindingContext.Result = ModelBindingResult.Success(value);
            return Task.CompletedTask;
        }
    }

    // In Startup.cs
    services.AddControllers(options =>
    {
        options.ModelBinderProviders.Insert(0, new CustomModelBinderProvider());
    });
Enter fullscreen mode Exit fullscreen mode

Custom model binders help you deal with non-standard binding requirements.

4. Understanding .NET Core Garbage Collection and Performance

Garbage Collection in .NET Core handles the memory allocation and deallocation. Understanding how to make it work and how to optimize it, is important for performance.

Question: How does the Garbage Collection work in .NET Core, and what are some of the performance optimization techniques?

Answer: .NET Core makes use of a generational garbage collector comprising three generations of objects:

  • Generation 0: Short-lived objects. Frequently collected.

  • Generation 1: Objects that survive a GC from Generation 0.

  • Generation 2: Long-lived objects. Collected less frequently.

Optimization Techniques:

  • Minimize allocations: Reduce the frequency and size of object allocations.

  • Use object pooling: Reuse objects to avoid frequent allocations.

  • Avoid large object heap (LOH) fragmentation: Allocate large objects infrequently or use ArrayPool them for array management.

    Good management of GC enables the application’s performance and responsiveness.

5. Tag Helpers

The ASP.NET Core Tag Helpers allow you to render HTML elements in an even more readable and reusable manner.

Question: What is a Tag Helper? How to use and implement a custom Tag Helper in ASP.NET Core?

Answer: Tag Helpers enable server-side code participation in generating and rendering HTML elements. To create a custom Tag Helper:

  1. Create a Tag Helper class: Create a class for your Tag Helper. Inherit from TagHelper and override the Process method.

  2. Register the Tag Helper: Ensure it’s available in your views.

Example:

    [HtmlTargetElement("my-custom-tag")]
    public class MyCustomTagHelper : TagHelper
    {
        public string Text { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.Content.SetContent(Text);
        }
    }
    // Usage in a Razor view
    <my-custom-tag text="Hello, Tag Helpers!"></my-custom-tag>
Enter fullscreen mode Exit fullscreen mode

Tag Helpers make the code look cleaner and simpler to read within your Razor views.

6. Understanding .NET Core Security Features: Authentication and Authorization

Security is a key component of any application. In general, authentication and authorization are at the hub of securing an application in .NET Core.

Question: How would you implement authentication and authorization in ASP.NET Core? What is an example of implementing cookie-based authentication?

Answer: Configure authentication and authorization in Startup.cs:

Add Authentication Services:

    public void ConfigureServices(IServiceCollection services) {     
       services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)             
       .AddCookie(options =>             
       {                 
          options.LoginPath = "/Account/Login";                 
          options.LogoutPath = "/Account/Logout";             
        });          
       services.AddAuthorization(); 
    }

**Use Authentication Middleware:**

    public void Configure(IApplicationBuilder app) {     
       app.UseAuthentication();     
       app.UseAuthorization(); 

    }
Enter fullscreen mode Exit fullscreen mode

These options will enable you to utilize and manage user authentication along with access to resources.

7. Advanced Configuration: IConfiguration and Configuration Providers

Configuration interface, IConfiguration and the configuration providers will help you deal with application settings through different sources like JSON files, and environment variables amongst others.

Question: How to access settings using IConfiguration from various .NET Core configuration sources? Provide an example.

Answer: You may use IConfiguration to access the settings from different sources configured in Startup.cs

Example:

    public class MyService
    {
        private readonly string _connectionString;
        public MyService(IConfiguration configuration)
        {
            _connectionString = configuration.GetConnectionString("DefaultConnection");
        }
    }
    // In Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        // Configuration sources are added here
        Configuration.GetSection("MySettings");
    }
Enter fullscreen mode Exit fullscreen mode

You can have several configuration providers in order to load the settings from different sources, hence managing the settings as flexible as possible.

So, how did you do?

If you know the concept with confidence and understand the code examples, you’re likely well-versed in it .NET.

Let’s keep the conversation going and help each other grow as .NET professionals.

Happy coding!

Top comments (0)