Explain the different types of Dependency Injection:
There are three types of Dependency Injection
- Transient
- Scoped
- Singleton
1. Transient
When ever you want to create a new instance of service object every time the object is injected in to different components of the app.
Example:
If an service is injected/used in Class A and B, then a new instance of the service is created by the DI
Usage:
Mainly used for stateless operations like formatting…
2. Scoped
When ever you want to create a new instance of service object every time a new HTTP request is made. However, the same object is reused in the different places the object is injected. No new object needs to be created.
Note: If you open a new tab and hit the same endpoint API, then it is considered a separate HTTP request which will result in creating a new service object.
Usage:
If you want to maintain the state of an object across different components of the app. For example, you have created the order and want to maintain the state of the order across several pages/parties of the page.
May be a shopping cart object can be injected as a scoped to keep the state of the object with you across different controllers or classes.
Another scenarios may be managing session object. Session store the state of an object and it should be available when you navigate through the app from one control to the other.
Another scenario is reusing same DB connections within same HTTP request.
Another scenario is for logging. You may want to use the same object for logging error which may have relevant info about the error in previous controllers and you want to append the error across several components of the app.
It should not be used as singleton due to concurrency issues. This leads us to our last type of DI:
3. Singleton
In singleton DI, once the service is created in the first HTTP request, the same object is reused in the subsequent HTTP requests of same app.
Usage:
Use singleton for very expensive operation like cacheing
Cache requires to store the state of a very big object possibly what you read from DB that will expire in 30 minute or so which might be expensive to recreate every time you get a new HTTP request
———
Here are some more advanced .NET Core MVC Web API interview questions to help you prepare for your interview:
1. Explain the differences between ASP.NET Core MVC and ASP.NET Web API.
- ASP.NET Core MVC is primarily used for building web applications with user interfaces, whereas ASP.NET Core Web API is used for creating RESTful APIs to serve data to clients, often as JSON or XML.
2. What is attribute routing in ASP.NET Core MVC? How does it differ from convention-based routing?
- Attribute routing allows you to define routing rules directly on controller actions or at the controller level using attributes like `[Route]`. Convention-based routing relies on naming conventions to map URLs to controller actions. Attribute routing provides more flexibility and control over route definitions.
3. Explain how model binding works in ASP.NET Core MVC.
- Model binding is the process of mapping incoming HTTP request data to action method parameters or model classes. ASP.NET Core MVC uses model binding to automatically convert request data (e.g., form values, route values, query strings) into method parameters or objects.
4. What are content negotiation and media types in ASP.NET Core Web API?
- Content negotiation is the process of selecting the appropriate response format (media type) based on the client's preferences and the server's capabilities. Media types (e.g., JSON, XML) specify the format of data exchanged between the client and the API.
5. What is dependency injection, and why is it important in ASP.NET Core?
- Dependency injection is a design pattern and a built-in feature in ASP.NET Core that allows you to inject dependencies (e.g., services, components) into your application's components, promoting modularity, testability, and maintainability.
6. Explain the use of action filters in ASP.NET Core MVC. Provide examples of scenarios where you would use them.
- Action filters are attributes that can be applied to controller actions to perform custom logic before or after the action is executed. They are used for tasks such as authentication, logging, and caching. Examples include `[Authorize]`, `[ValidateAntiForgeryToken]`, and custom filters.
7. What is JWT (JSON Web Token), and how is it used for authentication in ASP.NET Core Web API?
- JWT is a compact, self-contained token format used for securely transmitting information between parties. In ASP.NET Core Web API, JWTs are commonly used for implementing token-based authentication, where the server issues tokens to authenticated users, and clients include the token in subsequent requests.
8. What is CORS (Cross-Origin Resource Sharing), and why is it important in Web API development?
- CORS is a security feature that controls which domains can access resources (e.g., APIs) from another domain. In ASP.NET Core Web API, CORS policies are used to specify which origins are allowed to make requests to the API, helping to prevent unauthorized access.
9. Explain how to implement versioning in ASP.NET Core Web API. Why might versioning be necessary for an API?
- API versioning allows you to provide multiple versions of your API to accommodate changes and backward compatibility. ASP.NET Core Web API supports versioning through URL path, query string, or header versioning. It is essential for maintaining existing clients while introducing new features or changes.
Why is API Versioning Necessary? API versioning is essential in API development for several reasons:
Backward Compatibility: As your API evolves, you may need to make changes to existing endpoints or introduce new features. API versioning allows you to do this while ensuring that existing clients continue to work with the older version of the API. This prevents breaking changes.
Client Needs: Different clients may require different versions of your API. Some clients may not be ready to migrate to a newer version immediately, while others may need the latest features. Versioning enables you to cater to the diverse needs of your client base.
Granular Control: Versioning provides granular control over which features and changes are available to clients. It allows you to deprecate and remove older versions when they are no longer needed or supported.
How to Implement API Versioning in ASP.NET Core Web API: ASP.NET Core provides multiple approaches to implement API versioning:
URL Path Versioning: In this approach, the version is specified directly in the URL path. For example:
To implement URL path versioning, you can use the Microsoft.AspNetCore.Mvc.Versioning package.
https://api.example.com/v1/products
https://api.example.com/v2/products
Query String Versioning: In this approach, the version is specified using a query string parameter. For example:
This approach is more flexible and does not affect the URL structure significantly.
https://api.example.com/products?api-version=1.0
https://api.example.com/products?api-version=2.0
Header Versioning: In this approach, the version is specified in a custom HTTP header. This can be useful when you want to keep URLs clean and standardize versioning across different endpoints.
GET /products HTTP/1.1
Host: api.example.com
Api-Version: 1.0
Implementation Steps:
Install the appropriate versioning package, such as Microsoft.AspNetCore.Mvc.Versioning, via NuGet.
Configure versioning in the Startup.cs file's ConfigureServices method:
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
This code sets up default versioning behavior and specifies version 1.0 as the default.
Apply versioning attributes to your controllers or actions to indicate which version(s) they support:
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase
{
// Controller actions for version 1.0
}
Test your API by specifying the desired version in the URL, query string, or headers, depending on your chosen versioning approach.
API versioning is a powerful tool for managing the evolution of your API while ensuring that existing clients remain functional. It provides flexibility and control over how clients interact with different versions of your API, making it a crucial aspect of API design and maintenance.
10. What is Swagger/OpenAPI, and how can it be used to document ASP.NET Core Web APIs?
- Swagger/OpenAPI is a specification for documenting APIs. In ASP.NET Core Web API, the Swashbuckle library is often used to generate Swagger documentation automatically. It provides a user-friendly interface for developers to understand and test the API's endpoints.
These advanced ASP.NET Core MVC Web API interview questions cover topics like routing, model binding, authentication, dependency injection, and API documentation. Be prepared to provide practical examples and discuss real-world scenarios during your interview.