【问题标题】:Error using unity in mapping objects in MVC在 MVC 中映射对象时使用统一时出错
【发布时间】:2014-11-04 20:37:31
【问题描述】:

我发现在控制器构造函数中使用 unity 存在问题。以下是详细信息-

在单元配置中(unity.config)——这就是我正在做的——

container.RegisterType<ISessionWrapper, SessionWrapper>()

在控制器构造函数中

    public OnboardingController( ISessionWrapper sessionwrapper )
    {
        SessionWrapper = sessionwrapper;
    }

SessionWrapper

公共接口 ISessionWrapper { 字符串品牌{得到;放; } //字符串 CurrenSessionCulture { get;放; } }

public class SessionWrapper : ISessionWrapper
{
    public string Brand
    {
        get;
        set;
    }
}

执行此操作时发生错误

没有为此对象定义无参数构造函数。 说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。 异常详细信息:System.MissingMethodException:没有为此对象定义无参数构造函数。

来源错误: 在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。****

当我像这样更改控制器构造函数定义时,一切正常。

    public OnboardingController()
        : this(new SessionWrapper())
    {
        //
    }

【问题讨论】:

  • 你在配置代码中调用 DependencyResolver.SetResolver() 吗?
  • 你是如何构建(创建)你的 OnboardingController 的?
  • 你在使用 PerRequestLifetimeManager 吗?

标签: c# asp.net-mvc asp.net-mvc-4 c#-4.0 unity-container


【解决方案1】:

您需要使用 Unity 使用自定义 ControllerFactory 来解析控制器类的实例。 MVC 使用的默认 ControllerFactory 要求控制器类具有无参数构造函数。

使用 Unity 的自定义 ControllerFactory 看起来像

public class UnityControllerFactory : DefaultControllerFactory {
  private readonly IUnityContainer _container;

  public UnityControllerFactory (IUnityContainer container) {
    _container = container;
  }

  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {
    if (controllerType != null) {
        return _container.Resolve(controllerType) as IController;
    }
    else {
        return base.GetControllerInstance(requestContext, controllerType);
    }
  }
}

在应用程序启动时(通常在 global.asax 中),您使用以下代码在 MVC 运行时注册您的 ControllerFactory

var container = // initialize your unity container
var factory = new UnityControllerFactory(container);
ControllerBuilder.Current.SetControllerFactory(factory);

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多