Monday, January 12, 2015

the way to get rid of ObjectFactory in StructureMap implementations

...seems to be tied to the new magic of having StructureMap hydrate interfaces that are called out at MVC controller constructors. So, what does one do in the web forms world? As best as I can tell that space has just been left to be. I have tried to minimize the use of ObjectFactory by having a static (factory) class with static methods keeping all of the callouts to ObjectFactory in a web forms app. I called my class ExternalDependencies, it lived in the UI project, and one just went to ExternalDependencies to get interfaces for, um, external dependencies. My superior suggested that instead it would be better to introduce a middleman between each web form code behind and System.Web.UI.Page like so:

using Whatever.Logging;
using StructureMap;
namespace Stuff.UserInterface
{
   public class BasePage : System.Web.UI.Page
   {
      private ILogger _logger;
      public ILogger Logger
      {
         get
         {
            if (_logger == null)
            {
               _logger = ObjectFactory.GetInstance<ILogger>();
            }
            return _logger;
         }
      }
   }
}

 
 

The way this works is the code behind inherits from BasePage and then uses Logger whenever it needs whatever it is the Logger decouples from the code behind. When I changed the inheritance at the .cs files, I feared that the .designer.cs dance partners would also need updating too, but, as it turns out, in a partial class paradigm only one of the partial classes in a set or group needs to denote inheritance. Note: The code behind for a master page inheirts from System.Web.UI.MasterPage instead of System.Web.UI.Page. This modestly complicates this idea of using a middleman to keep token references to ObjectFactory, especially so if you don't want to break the DRY (don't repeat yourself) rule by making a middleman between the master page and System.Web.UI.MasterPage. Hmmmm. What do to?

No comments:

Post a Comment