1

我正在使用StructureMap来解析依赖关系,它可以在早期版本中正常工作。但是在更新StructureMap版本4.2.0.40后,我正面临着这个错误。StructureMap:名称'ObjectFactory'在当前上下文中不存在

ObjectFactory现在已在新版本中废弃。 那么如何修改以下逻辑以适应更新版本。

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) 
     { 
      try 
      { 
       if ((requestContext == null) || (controllerType == null)) 
        return null; 

       return (Controller)ObjectFactory.GetInstance(controllerType); 
      } 
      catch (StructureMapException) 
      { 
       System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave()); 
       throw new Exception(ObjectFactory.WhatDoIHave()); 
      } 
     } 

Bootstrapper.cs

public static class Bootstrapper 
    { 
     public static void Run() 
     { 
      ControllerBuilder.Current 
       .SetControllerFactory(new StructureMapControllerFactory()); 

      ObjectFactory.Initialize(x => 
      { 
       x.AddConfigurationFromXmlFile(@"D:\Samples\Web_API\OneCode\StructureMap.Web\StructureMap.Web\StructureMap.xml"); 
      }); 
     } 
    } 
} 

回答

2

您必须添加的ObjectFactory自己的实现,是这样的:

public static class ObjectFactory 
{ 
    private static readonly Lazy<Container> _containerBuilder = 
     new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication); 

    public static IContainer Container 
    { 
     get { return _containerBuilder.Value; } 
    } 

    private static Container defaultContainer() 
    { 
     return new Container(x => 
     { 
      // default config 
     }); 
    } 
} 

详情请参阅here

或者返回使用旧版本的StructureMap。