Singleton Design Pattern in an ASP.NET Core Web API using a Three-Tier Architecture for a model named CSharpCornerArticle with complete CRUD operations.
Step 1. Create CSharpCornerArticle Model
Firstly, let's define the CSharpCornerArticle model:
// Sardar Mudassar Ali Khan
public class CSharpCornerArticle
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
// Add other properties as needed
}
Step 2. Create Data Access Layer
Next, let's create the Data Access Layer (DAL) responsible for handling data operations. Here, we'll use a Singleton pattern for the data context:
// Sardar Mudassar Ali Khan
// Data Access Layer
public class CSharpCornerArticleRepository
{
private static CSharpCornerArticleRepository _instance;
private List<CSharpCornerArticle> _articles;
private CSharpCornerArticleRepository()
{
_articles = new List<CSharpCornerArticle>();
// You can initialize data or connect to a database here
}
public static CSharpCornerArticleRepository Instance
{
get
{
if (_instance == null)
{
_instance = new CSharpCornerArticleRepository();
}
return _instance;
}
}
public List<CSharpCornerArticle> GetAllArticles()
{
return _articles;
}
public CSharpCornerArticle GetArticleById(int id)
{
return _articles.FirstOrDefault(a => a.Id == id);
}
public void AddArticle(CSharpCornerArticle article)
{
// Add validation and error handling as needed
_articles.Add(article);
}
public void UpdateArticle(CSharpCornerArticle article)
{
// Add validation and error handling as needed
var existingArticle = _articles.FirstOrDefault(a => a.Id == article.Id);
if (existingArticle != null)
{
existingArticle.Title = article.Title;
existingArticle.Content = article.Content;
// Update other properties as needed
}
}
public void DeleteArticle(int id)
{
// Add validation and error handling as needed
var articleToRemove = _articles.FirstOrDefault(a => a.Id == id);
if (articleToRemove != null)
{
_articles.Remove(articleToRemove);
}
}
}
Step 3. Create a Services layer
Now, let's create a Service Layer to interact with the Data Access Layer:
// Sardar Mudassar Ali Khan
// Service Layer
public class CSharpCornerArticleService
{
private readonly CSharpCornerArticleRepository _repository;
public CSharpCornerArticleService()
{
_repository = CSharpCornerArticleRepository.Instance;
}
public List<CSharpCornerArticle> GetAllArticles()
{
return _repository.GetAllArticles();
}
public CSharpCornerArticle GetArticleById(int id)
{
return _repository.GetArticleById(id);
}
public void AddArticle(CSharpCornerArticle article)
{
_repository.AddArticle(article);
}
public void UpdateArticle(CSharpCornerArticle article)
{
_repository.UpdateArticle(article);
}
public void DeleteArticle(int id)
{
_repository.DeleteArticle(id);
}
}
Join the conversation! Your thoughts help the community grow.