How to use Dependency Injection with ASP.NET Web Forms

前端 未结 6 1635
一生所求
一生所求 2020-11-27 14:02

I am trying to work out a way to use dependency injection with ASP.NET Web Forms controls.

I have got lots of controls that create repositories directly, and use tho

6条回答
  •  时光取名叫无心
    2020-11-27 15:07

    This is a solution I recently used to avoid hooking into the pipeline (I find that confuses everyone that looks at my code in the future, but yes, I see its benefits as well):

    public static class TemplateControlExtensions
    {
        static readonly PerRequestObjectManager perRequestObjectManager = new PerRequestObjectManager();
    
        private static WIIIPDataContext GetDataContext(this TemplateControl templateControl)
        {
            var dataContext = (WIIIPDataContext) perRequestObjectManager.GetValue("DataContext");
    
            if (dataContext == null) 
            {
               dataContext = new WIIIPDataContext();
               perRequestObjectManager.SetValue("DataContext", dataContext);   
            }
    
            return dataContext;
        }
    
        public static IMailer GetMailer(this TemplateControl templateControl)
        {
            return (IMailer)IoC.Container.Resolve(typeof(IMailer));
        }
    
        public static T Query(this TemplateControl templateControl, Query query)
        {
            query.DataContext = GetDataContext(templateControl);
            return query.GetQuery();
        }
    
        public static void ExecuteCommand(this TemplateControl templateControl, Command command)
        {
            command.DataContext = GetDataContext(templateControl);
            command.Execute();
        }
    
        private class PerRequestObjectManager
        {
            public object GetValue(string key)
            {
                if (HttpContext.Current != null && HttpContext.Current.Items.Contains(key))
                    return HttpContext.Current.Items[key];
                else
                    return null;
            }
    
            public void SetValue(string key, object newValue)
            {
                if (HttpContext.Current != null)
                    HttpContext.Current.Items[key] = newValue;
            }
        }
    }
    

    This shows how you can create your own life time manager pretty easily as well as hook into an IoC container if you so desire. Oh, and I am also using a query/command structure which is sort of unrelated, but more on the reasoning behind that can be found here:

    Limit your abstractions: Refactoring toward reduced abstractions

提交回复
热议问题