c# - Controller 中的 IoC 容器实现

标签 c# asp.net-mvc inversion-of-control structuremap

我想在一种方法中使用 IoC 容器来检查登录用户提交付款时的公司代码。我的设置类中有两个证书和一个 IF else 语句来区分每个证书。

      public static string FDGCreditCardUserID
    {
        get
        {
            if (BillingController.currentcompanycode == 5)
                return ConfigurationManager.AppSettings["5FDGCreditCardUserID"];
            else
                return ConfigurationManager.AppSettings["6FDGCreditCardUserID"];
        }
    }
    public static string FDGCreditCardPassword
    {
        get
        {
            if (BillingController.currentcompanycode == 5)
                return ConfigurationManager.AppSettings["5FDGCreditCardPassword"];
            else
                return ConfigurationManager.AppSettings["6FDGCreditCardPassword"];
        }
    } 

然后在我的 IoC 容器中

  x.For<IFDGService>().Use<FDGService>().SetProperty(s =>
            {
                s.Url = Settings.FDGURL;
                s.UserID = Settings.FDGCreditCardUserID;
                s.Password = Settings.FDGCreditCardPassword;
                s.Certificate = Settings.FDGCreditCardCertFilePath;  
            });

我有一个 FDGService 检查凭据,但不会在提交付款时返回 IoC 以检查公司代码并应用正确的证书。

SubmitPayment 方法,其中信用卡控件在我运行时包含正确的公司代码。

如何让我的应用程序根据更新的公司代码选择正确的证书。鉴于用户可以根据选择的付款政策拥有不同的公司代码。一个公司代码目前可以是 5 或 6。

  public ActionResult SubmitPayment([ConvertJSON]List<PayModel> payments)
    {  
        List<TransactionModel> transactions = new List<TransactionModel>();
        foreach (var pymt in payments)
        {
            var policyNumber = pymt.PolicyNumber.Trim();
            TransactionModel trans = new TransactionModel() { Payment = pymt };

            if (pymt.Selected)
            {
                var creditCardControl = UpdateCreditCardControl(policyNumber);

最佳答案

如果您正在使用 StructureMap,它会使用“贪心初始化”,这意味着当调用构造函数时,它将调用传入的参数或参数数量最多的构造函数。

private IFDGService service;

public MyController(IFDGService service)
{
    this.service = service;
}

服务在调用IoC.Configure()后可用。

在应用程序启动的任何地方调用IoC.Configure()。谷歌“Mvc 从哪里开始”或类似的东西。

要更改公司代码,请将其设置在 Controller 中的实例变量以外的某个地方,例如 static 类,我知道静态是不好的,让它工作然后让它变得更好,因为那样会修改复杂,然后get; set; 当你需要的时候。

我要去开会,有点匆忙,希望对你有帮助

关于c# - Controller 中的 IoC 容器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31458560/

相关文章:

java - 一个简单的 IOC 容器类有什么问题?

c#-4.0 - 将同一接口(interface)的不同实现和配置注入(inject)到不同的客户端

c# - 连接不同数据库中的两个表

c# - 带字符串参数的 HttpClient GET 方法

asp.net-mvc - MVC : route config order routes

asp.net-mvc - 使用 catchall 通配符重定向到 Controller (但使用不同的主 Controller )

c# - 重载导致代码膨胀

c# - SQL 语法不正确?

c# - 如何在 Mongo 集合中查找最新文档 (C#)

spring - 是否可以在两个地方 Autowiring 原型(prototype)范围类的相同实例