Issues with my MVC repository pattern and StructureMap

后端 未结 3 2099
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 18:26

I have a repository pattern i created on top of the ado.net entity framework. When i tried to implement StructureMap to decouple my objects, i kept getting StackOverflowExce

3条回答
  •  梦谈多话
    2020-12-30 18:57

    I used a similar solution involving a generic implementor of IValidationDictionary uses a StringDictionary and then copied the errors from this back into the model state in the controller.

    Interface for validationdictionary

       public interface IValidationDictionary
        {
            bool IsValid{get;}
            void AddError(string Key, string errorMessage);
            StringDictionary errors { get; }
        }
    

    Implementation of validation dictionary with no reference to model state or anything else so structuremap can create it easily

    public class ValidationDictionary : IValidationDictionary
    {
    
        private StringDictionary _errors = new StringDictionary();
    
        #region IValidationDictionary Members
    
        public void AddError(string key, string errorMessage)
        {
            _errors.Add(key, errorMessage);
        }
    
        public bool IsValid
        {
            get { return (_errors.Count == 0); }
        }
    
        public StringDictionary errors
        {
            get { return _errors; }
        }
    
        #endregion
    }
    

    Code in the controller to copy the errors from the dictionary into the model state. This would probably be best as an extension function of Controller.

    protected void copyValidationDictionaryToModelState()
    {
        // this copies the errors into viewstate
        foreach (DictionaryEntry error in _service.validationdictionary.errors)
        {
            ModelState.AddModelError((string)error.Key, (string)error.Value);
        }
    }
    

    thus bootstrapping code is like this

    public static void BootstrapStructureMap()
    {
        // Initialize the static ObjectFactory container
        ObjectFactory.Initialize(x =>
        {
            x.For().Use();
            x.For().Use();
            x.For().Use(); 
        });
    }
    

    and code to create controllers is like this

    public class IocControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return (Controller)ObjectFactory.GetInstance(controllerType);
        }
    }
    

提交回复
热议问题