如何使用 Ninject 将 ModelState 作为参数注入?

How to inject ModelState as parameter with Ninject?

我对 Ninject 很陌生。我想找到一种方法将控制器的 Modelstate 进一步传递到服务层。

我现在拥有的:

       private readonly IAccountService service; 

       public AccountController(ILanguageService ls, ISessionHelper sh)
        {
            this.service = new AccountService(new ModelStateWrapper(this.ModelState));
            this.languageService = ls;
            this.sessionHelper = sh;

        }

    public AccountService(IValidationDictionary validationDictionary)
    {
        this.validationDictionary = validationDictionary;
    }

我想以某种方式到达:

       private readonly IAccountService service; 

       public AccountController(ILanguageService ls, ISessionHelper sh, IAccountService as)
        {
            this.service = as;
            this.languageService = ls;
            this.sessionHelper = sh;

        }

    public AccountService(IValidationDictionary validationDictionary)
    {
        this.validationDictionary = validationDictionary;
    }

但是就像您看到的那样,AccountService 将永远无法接收 IValidationDictionary,因为它从未作为参数从 AccountController 发送。

有可能实现吗?或者这只是我必须忍受的事情之一?

ModelState 是应用程序 runtime 状态的一部分。因此,在您使用 Ninject.

编写应用程序的时间点不可用

您可以通过创建 Abstract Factory 来解决此限制,从而创建您的 AccountService 并使其成为应用程序运行时状态的一部分。

public interface IAccountServiceFactory
{
    IAccountService Create(IValidationDictionary validationDictionary);
}

public class AccountServiceFactory
{
    public IAccountService Create(IValidationDictionary validationDictionary)
    {
        return new AccountService(validationDictionary);
    }
}

然后在您的 AccountController 中,注入 AccountServiceFactory 而不是 AccountService。

   private readonly IAccountServiceFactory serviceFactory; 

   public AccountController(ILanguageService ls, ISessionHelper sh, IAccountServiceFactory asf)
    {
        this.serviceFactory = asf;
        this.languageService = ls;
        this.sessionHelper = sh;

    }

    public void DoSomething()
    {
        var accountService = this.serviceFactory.Create(new ModelStateWrapper(this.ModelState));

        // Do something with account service
    }

或者,您可以在需要时通过每个 public 方法调用将运行时依赖项直接传递给帐户服务。

this.service.DoSomething(new ModelStateWrapper(this.ModelState));