Top .NET Core Interview questions

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

The .Net core is a high performance framework that can adapt to existing technologies. Its popularity is increasing due to its open source code and platform independence. Be prepared for an interview and make sure to read our .net core interview questions.

What is the difference between .Net Core and .Net Framework ?

  • .NET Framework is a traditional .NET platform. Console, desktop web and mobile applications can be developed with this platform. These applications only run on the Windows operating system. When we develop an application directly using .NET Framework, it is imperative that we use a heavy library called Framework Class Library, which contains all components.
  • .NET core is a new generation application platform that uses .NET Standard. It provides many advantages over the traditional version.
  • .Net Core is lightweight and modular. With this structure, only needed modules are used, unnecessary modules are not loaded, so there is no need to load the whole .NET infrastructure on its back, so to speak
  • .Net Core is platform independent, it works on all operating systems. On Windows, Linux and even MacOS.

When should you pick .Net Core or .Net Framework for you application ?

In the following cases, you should pick .Net Core:

  1. If you need to make a multi-platform application and if it will run on several different operating systems.
  2. If you will develop applications in microservices architecture.
  3. If an application will be run on Docker containers.
  4. If you need to develop applications running on Windows, Mac or Linux.
  5. If you need to use various .NET versions in the same project.

In the following cases, you should pick .Net Framework:

  1. If you need to create Windows Forms and WPF applications.
  2. If you need to ASP.NET WebForms.
  3. If you need to create a WCF service.
  4. If you need to access Windows specific APIs.
  5. If you are using using third-party libraries or NuGet packages not available in .NET Core.
  6. If you use the platform which does not support .NET Core.

What is ASP.NET Core Middleware?

The .Net core middleware is the structures that serve to handle the process of the request from our application until it turns into a response. These structures allow us to do the necessary logging, authorization or the controls required by our application on the request and response. After each layer runs its own rule, it can decide whether the request should continue in the application or interrupt and return the response.

// This method gets called by the runtime. 
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
 
    app.UseRouting();
 
    app.UseAuthorization();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

The above code block shows the middleware coming by default in the .Net Core Mvc project.

What are the Types of Dependency Injection

  • Constructor Injection (All services that the class depends on must be injected into the constructor method.)
  • Property Injection (Dependencies are injected through public property by the services needed)
  • Method Injection(Dependencies are injected through public method by the services needed)

What is Dependency Injection and how do you implement it in .Net Core

Dependency Injection is a design pattern that is used to provide loosely coupled code in our developments and includes inversion of control and dependency inversion principles.In other words, it is a structure where we can work with interfaces instead of directly working with concrate classes, we can determine the concrate class that will work behind these interfaces, and manage the entire process related to the life time of the instance of this concrate class.

Dotnet Core does not need a 3rd party library for dependency injection because it contains build in form. For this reason, you do not need to implement any implementation to use dependency injection. In the simplest form, you can use ConfigureServices method in Startup.cs

public interface IExampleInterface
{
    string SayHello();
}
 
public class ExampleClass : IExampleInterface
{
    public string SayHello()
    {
        return "Hello!";
    }
}

public void ConfigureServices(IServiceCollection services)
{
    //Transient
    services.AddTransient<IExampleInterface, ExampleClass>();
 
    //Scoped
    services.AddScoped<IExampleInterface, ExampleClass>();
 
    //Singleton
    services.AddSingleton<IExampleInterface, ExampleClass();
}

What is the .Net Core CLI ?

.Net Core CLI (Command Line Interface) is a tool for developing,publishing,running,building .Net Core applications. If you install .Net SDK , .Net Core CLI ready for usage.

What is CTS?

CTS (Common Type System) determines how data types are defined, used and managed. The “int” data type in C # and the Integer data type in Visual Basic are used by CTS as Int32 after compilation.

What are Configuration Providers ?

Configuration providers are structures that read and make available key value data from various sources.

There are 3 different providers as JSON, command-line, environment variables that come built-in in .NET Core.

How do you implement a Custom Configuration Provider ?

In the example, we will keep the application settings in Redis and read the settings while starting the application.

public class RedisConfigurationProvider : ConfigurationProvider
{
    private readonly string _redisHost;
 
    public RedisConfigurationProvider(string redisHost)
    {
        _redisHost = redisHost;
    }
 
    public override void Load()
    {
        var options = ConfigurationOptions.Parse(_redisHost);
        var connectionMultiplexer = ConnectionMultiplexer.Connect(options);
        var redisSettings = connectionMultiplexer.GetDatabase().StringGet("Settings");
        var settings = JsonConvert.DeserializeObject(redisSettings);
 
        Data.Add("AppName", settings.AppName);
        Data.Add("AppVersion", settings.AppVersion);
    }
}

We are overriding the Load method in the base class in the “Configuration Provider” class we have written. In the “Load” method, we connect to Redis and read the related settings and fill in the content of the dictionary named data from the base class.

public class RedisConfigurationSource : IConfigurationSource
{
    private readonly string _redisHost;
 
    public RedisConfigurationSource(string redisHost)
    {
        _redisHost = redisHost;
    }
 
    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new RedisConfigurationProvider(_redisHost);
    }
}

Our Configuration Source class derives from the IConfigurationSource class. The IConfigurationSource interface has a method called “Build”. This class exists to represent a configuration provider. Our Configuration Source class represents RedisConfigurationProvider. Constructor takes the address of our Redis server as a parameter from the method.

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddRedisConfiguration(this IConfigurationBuilder configuration, 
         string redisHost)
    {
        configuration.Add(new RedisConfigurationSource(redisHost));
        return configuration;
    }
}

The purpose of this class is to add the object instance of our Configuration Source class to an object instance of type IConfigurationBuilder. In this way, our .NET Core application will now be able to read our application settings from Redis.

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
 
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(AddRedisConfiguration)
            .UseUrls("http://localhost:5000")
            .UseStartup()
            .Build();
 
    private static void AddRedisConfiguration(WebHostBuilderContext context, 
             IConfigurationBuilder builder)
    {
        var configuration = builder.Build();
        builder.AddRedisConfiguration("localhost");
    }
}

ConfigureAppConfiguration method takes a delegate as a parameter. Using the method we delegated and the AddRedisConfiguration extension method, we made .NET Core read our settings from Redis while our application was being loaded.

public class HomeController : Controller
{
    private readonly IConfiguration _appSettings;
 
    public HomeController(IConfiguration config)
    {
        _appSettings = config;
    }
 
    public IActionResult Index()
    {
        ViewBag.AppName = _appSettings.GetSection("AppName").Value;
        ViewBag.AppVersion = _appSettings.GetSection("AppVersion").Value;
 
        return View();
    }
}

With the help of Dependency Injection, we get an example of an object of type IConfiguration. In the index action, we read the AppName and AppVersion values ​​and assign them to ViewBags. AppName and AppVersion names are key fields that we added to Data Dictionary in our Configuration Provider class.

What are logging providers?

These are the providers that write the logs of the application to the desired environment (azure, database, output, kibana).

How do you implement logging providers ?

Before start to implementation there are some classes and interfaces to understand

  • ILogger (It is the signature of the class that will take responsibility for logging.)
  • Logger (It is the class that will take responsibility for logging.)
  • ILoggerProvider (It is the signature of the class that will take responsibility for the provider.)
  • LoggerProvider (It is the class that will take over the provider responsibility. Its task is to produce the “Logger” class.)
  • ILoggerFactory (It is the interface that incorporates the log mechanism into the application and generates the “LoggerProvider” class as a task.)

In our example we will be logging to a txt file.

First, let’s create the “Logger” class that will take responsibility for logging.

public class Logger : ILogger
{
        IHostingEnvironment _hostingEnvironment;

        public Logger(IHostingEnvironment hostingEnvironment) => _hostingEnvironment = hostingEnvironment;
        public IDisposable BeginScope<tstate>(TState state) => null;
        public bool IsEnabled(LogLevel logLevel) => true;
        
        public async void Log<tstate>(LogLevel logLevel, EventId eventId, TState state, 
              Exception exception, Func<tstate, exception,="" string=""> formatter)
        {
            using (StreamWriter streamWriter = new StreamWriter($"
            {_hostingEnvironment.ContentRootPath}/log.txt", true))
            {
                await streamWriter.WriteLineAsync($"Log Level : 
                {logLevel.ToString()} | Event ID 
                : {eventId.Id} | Event Name : {eventId.Name} | Formatter : {formatter(state, exception)}");
                streamWriter.Close();
                await streamWriter.DisposeAsync();
            }
        }
}

Let’s create the “LoggerProvider” class that will take the responsibility of the provider.The important point here is to create an object from the “Logger” class we created above in the “CreateLogger” method and return it.

public class LoggerProvider : ILoggerProvider
{
    public IHostingEnvironment _hostingEnvironment;
    public LoggerProvider(IHostingEnvironment hostingEnvironment) => _hostingEnvironment = hostingEnvironment;
    public ILogger CreateLogger(string categoryName) => new Logger(_hostingEnvironment);
    public void Dispose() => throw new NotImplementedException();
}

As a result of the structures we have created, we need to include an instance from the “Logger” class into the application via the provider class named “LoggerProvider” above. For this, we need to do the following work in the “Configure” method in the “Startup.cs” file.

public class Startup
{
    public Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment { get; set; }
    public Startup(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment) 
            => _hostingEnvironment = hostingEnvironment;
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddProvider(new LoggerProvider(_hostingEnvironment));
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        app.UseRouting();
        app.UseEndpoints(_ => _.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"));
    }
}

If you examine the code block above, the “ILoggerFactory” parameter has been added to the “Configure” method. A “LoggerFactory” instance in the Runtime will be connected to the relevant parameter from the application core, and the “LoggerProvider” object and log mechanism will be integrated into the system through this instance.

What we need to do now is to make a request to the “Logger” object with Dependency Injection in the relevant Controller and to get the necessary logs from this object at the desired point.

public class HomeController : Controller
{
	public ILogger<homecontroller> _logger;
	public HomeController(ILogger<homecontroller> logger) => _logger = logger;
	public IActionResult Information()
	{
		_logger.LogInformation("Information mesajı...");
		return View();	
	}	
	public IActionResult Error()
	{
		_logger.LogError("Error mesajı...");
		return View();
	}
	public IActionResult Warning()
	{
		_logger.LogWarning("Warning mesajı...");
		return View();		
	}
}

As seen in the code block above, different log functions have been called on three different actions, namely “Information”, “Error” and “Warning”, in the “Home (Controller) .cs” class. When the application is compiled and executed, the content of the “log.txt” file created in the application directory as a result of the requests made to the above actions will be filled.

What is a .NET Generic Host ?

The generic host is a host mechanism that was announced with the 2.1 version of the .net core, enabling us to host applications in different protocols (tcp, udp etc), host applications running in the background, and use features such as dependency injection and logging, even in the console application.

How do you implement Asynchronous Programming?

There are 2 keywords required for asynchronous programming in .net core: Await and Async. Their use is as follows

ublic class AsyncExample
{
    public async Task<string> GetName() 
    {
        return "Chubby";
    }
 
    public async Task<string> GetFullName()
    {
        var name = await GetName();
        return $"{name} Developer"; 
    }
}

What are the dependency Injection Lifetime ?

  • Transient (New object instance is created every time it is requested)
  • Scoped (Used by all units that request an object instance created within the same scope.)
  • Singleton (Created once and all requesting units use the same object instance)

What is a Startup class and what is it used for ?

Startup class contains the services required for the application and includes the Request Handling Pipeline. Optionally, it includes a ConfigureServices method to configure the application’s services.

Services are components used by the application. Log service can be given as a classic example. Services are reusable components that provide the functionality of the application. Services are registered in ConfigureServices, and DI or

ApplicationServices across the application used through. It includes the Configure method to create the application’s request handling pipeline. ConfigureServices and Configure methods are called by the Asp.Net Core runtime when the application is running.

What are the two Hosting Models in .Net Core

  • In process Hosting Model (In this model, only one web server is used (such as IIS, Nginx, Apache). The application is hosted directly in these servers.)
  • Out of process Hosting Model (In this model, Kestrel can be used directly as a web server or requests can be directed to the Kestrel server with the help of a proxy server (IIS, NGINX, Apache).)

Before .Net Core 2.2 version there is only hosting model which Out of process.Today, with the .Net Core 3.1 version, the In process hosting model has been used by default.

How do you setup multiple environments in .net core

.Net Core determines the behavior of your application with the environment variable you set for the runtime environment. This value is automatically considered “Production” if you have never set it.

At startup of the application, .Net Core reads the value of the ASPNETCORE_ENVIRONMENT global variable and sets it to the IHostingEnvironment.EnvironmentName property.

You can change the application behavior according to the environment. In the code block below, it is decided which exception page will be shown in which environment.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
 
    if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Custom_Stage"))
    {
        app.UseExceptionHandler("/Error");
    }
 
    app.UseStaticFiles();
    app.UseMvc();
}

What languages are supported in .NET Core?

C#,F# and Visual Basic fully supports by .Net Core

What’s is .NET 5 ?

.Net 5 is a framework that gathers all frameworks (.Net Core, .Net Framework, Xamarin etc) developed by Microsoft, which Microsoft planed to release in November 2020.

Final Thoughts and Recommendations

The .Net core continues to be the popular framework of recent times. It made a name for itself especially with its 3.x versions. It is preferred through to its modular structures, micro service compatibility and high performance. Being a .Net Core developer will greatly benefit your career.Final Thoughts and Recommendations

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.