我一直在阅读大量关于通过 Ninject 进行依赖注入的阅读和教程,希望将来能够重构我的一个应用程序,使其更加灵活和可扩展。我的 Web 应用程序建立在一个 API 之上,可以让我访问后端基础架构。
我试图清理的部分技术债务是我必须进行的每一个 API 调用所带来的重复代码。API 有大约 45-50 种用于获取和管理不同实体的方法。
以下(非常简化的)代码示例说明了在我的代码中随处可见的重复模式。Ninject/DI 可以帮助我简化事情吗?
namespace MyApp
{
public class example
{
public static WebAccount Fetch_Account(Guid accountID)
{
//Create instance of API, request and response objects
WebAPI api = new WebAPI();
Fetch_Account_Request accountRequest = new Fetch_Account_Request();
Fetch_Account_Response accountResponse = new Fetch_Account_Response();
//Api call security signature
ApiSecuritySignature signature = new ApiSecuritySignature(/*My API ID */, /*My API Key */);
accountRequest.API_ID = /* My API ID */;
accountRequest.Token = signature.Token;
accountRequest.TimeStamp = signature.Date;
//Id of the account to be fetched
accountRequest.Account_ID = accountID;
//Fetch the account
accountResponse = api.Fetch_Account(accountRequest);
return accountResponse.Account;
}
public static void Manage_Account(WebAccount account)
{
//Create instance of API, request and response objects
WebAPI api = new WebAPI();
Manage_Account_Request manageAccountRequest = new Manage_Account_Request();
Manage_Account_Response manageAccountResponse = new Manage_Account_Response();
//Api call security signature
ApiSecuritySignature signature = new ApiSecuritySignature(/*My API ID */, /*My API Key */);
manageAccountRequest.API_ID = /* My API ID */;
manageAccountRequest.Token = signature.Token;
manageAccountRequest.TimeStamp = signature.Date;
//account to modify
manageAccountRequest.Account_ID = account.Account_ID;
//set Account properties
manageAccountRequest.Email = account.Email;
manageAccountRequest.Address_1 = account.Address_1;
manageAccountRequest.City = account.Postal_Zip;
manageAccountRequest.Postal_Zip = account.Postal_Zip;
manageAccountRequest.Country = account.Country;
manageAccountRequest.State = account.State;
//Make the call
manageAccountResponse = api.Manage_Account(manageAccountRequest);
}
}
}
应该注意的是,我无法访问所有请求和响应对象的代码,它们是我引用的共享库的一部分。