我希望能夠使用RunApp方法StartUp在我的控制臺應用程式中使用我的類運行我的static void Main方法。問題是我在StartUp帶有建構式的類中使用依賴注入來與其他帶有方法的類一起創建一個實體。但我不知道如何繼續,所以我可以在 static void Main 中使用我的 RunApp 方法。
我試過用
StartUp s = new StartUp();
s.RunApp();
但是好像不行,我得有引數才能輸入。
創業班:
public class StartUp : IStartUp
{
private readonly AddCustomer _addCustomer;
private readonly Booking _booking;
private readonly GetCustomer _getCustomer;
private readonly Service _service;
public StartUp(
AddCustomer addCustomer,
Booking booking,
GetCustomer getCustomer,
Service service)
{
_addCustomer = addCustomer;
_booking = booking;
_getCustomer = getCustomer;
_service = service;
}
public void RunApp()
{
Console.WriteLine(
"Hi! Welcome to Kennel GoldenRetriver. What would you like to do?");
Console.WriteLine("Press 1 to register a new customer and dog");
Console.WriteLine("Press 2 to show all customers");
Console.WriteLine("Press 3 to get all dogs");
Console.WriteLine("Press 4 to show customers and thier related dogs");
Console.WriteLine("Press 5 to leave dog on service");
Console.WriteLine("Press 6 to show all dogs on service");
Console.WriteLine("Press 7 to get your dog from service");
bool isNumber = int.TryParse(Console.ReadLine(), out int start);
if (isNumber)
{
switch (start)
{
case 1:
_addCustomer.AddCustomers();
break;
case 2:
_getCustomer.GetCustomers();
break;
case 3:
_getCustomer.GetDogs();
break;
case 4:
_getCustomer.GetRelatedCustomerToDog();
break;
case 5:
_booking.AddBooking();
_service.AddService();
break;
case 6:
_service.AddService();
break;
case 7:
_service.DeleteFromService();
break;
default:
Console.WriteLine("Please enter valid number");
break;
}
}
else
{
Console.WriteLine("Enter a number");
}
}
}
我的主要方法
class Program
{
static void Main(string[] args)
{
StartUp s = new StartUp();
s.RunApp();
}
}
uj5u.com熱心網友回復:
主題類需要滿足其所有依賴項,以便根據需要對其進行初始化。
所以要么通過Pure DI提供它們
class Program {
static void Main(string[] args) {
//...assuming the dependencies don't have dependencies themselves.
AddCustomer addCustomer = new();
Booking booking = new();
GetCustomer getCustomer = new();
Service service = new();
StartUp s = new StartUp(addCustomer, booking, getCustomer, service);
s.RunApp();
}
}
或通過控制反轉 (IoC) 容器,該容器將為您完成初始化和注入所有已注冊依賴項的繁重作業。
使用默認 .Net Core 容器的簡單示例
class Program {
static void Main(string[] args) {
IServiceProvider services = new ServiceCollection()
.AddTransient<AddCustomer>()
.AddTransient<Booking>()
.AddTransient<GetCustomer>()
.AddTransient<Service>()
.AddTransient<StartUp>()
.BuildServiceProvider();
StartUp s = services.GetService<StartUp>();
s.RunApp();
}
}
在過度簡化的純 DI 示例中,如果這些依賴項中的任何一個具有顯式依賴項,那么也需要滿足這些依賴項,以便在初始化主題型別時所有要求都可用。
根據程式的復雜性和大小,選擇權在您手中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/387510.html
