I have a .NET 6 Console app with a Product
class, which depends on IDatabase
.
Product.cs
public class Product
{
private readonly IDatabase databaseConnection;
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
private int StockQuantity { get; set; }
public Product(string name, decimal price, string category, int stockQuantity, IDatabase databaseConnection)
{
this.databaseConnection = databaseConnection;
//Id = productId;
Name = name;
Price = price;
Category = category;
StockQuantity = stockQuantity;
CreateProduct();
}
//some code
}
Questions:
- How should my Program.cs look like making sure I use DI?
- What would be a better approach to initialize the attributes if I do not want to pass it in a constructor?
Currently this is what I have in Program.cs, but this gives an error since Product
also requires IDatabase
dependency which I already added in the container:
Program.cs
var host = CreateHostBuilder(args).Build();
host.Run();
static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
string connectionString = hostContext.Configuration.GetConnectionString("DefaultConnection");
services.AddSingleton(new DatabaseConnection(connectionString));
services.AddTransient(new Product("",4,"",4));
});
}
Alternate
Here, instead of passing the attributes to constructor, I declared them in a method. This resolves the DI issue. But I am still not sure how to resolve the previous problem, and which approach would be better?
var host = CreateHostBuilder(args).Build();
var product = host.Services.GetRequiredService\();
product.SetProductDetails(1, "Sample Product", 49.99m, "Electronics", 100);
host.Run();