我对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发送。
有可能实现这一目标吗?或者这只是我必须忍受的事情之一?
答案 0 :(得分:2)
ModelState是应用程序的运行时状态的一部分。因此,在使用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
}
或者,您可以通过每个需要的公共方法调用将运行时依赖项直接传递给帐户服务。
this.service.DoSomething(new ModelStateWrapper(this.ModelState));