How to inject ModelState as parameter with Ninject?

后端 未结 1 1674
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 16:30

Im very new to Ninject. I want to find a way to pass Modelstate of a controller further to service layer.

what i have right now:

       private readonl         


        
相关标签:
1条回答
  • 2021-01-21 17:02

    ModelState is part of the application's runtime state. Therefore, it is not available at the point in time when you compose the application with Ninject.

    You could work around this limitation by creating an Abstract Factory to create your AccountService and also make it a part of your application's runtime state.

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

    And then in your AccountController, inject an AccountServiceFactory instead of an 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
        }
    

    Alternatively, you could pass the runtime dependency directly to the account service through each public method call where it is required.

    this.service.DoSomething(new ModelStateWrapper(this.ModelState));
    
    0 讨论(0)
提交回复
热议问题