Structuremap不适用于MVC4

时间:2012-03-04 18:11:20

标签: asp.net-mvc asp.net-mvc-3 inversion-of-control structuremap asp.net-mvc-4

我在MVC2 / 3中多次使用StructureMap而没有任何顾虑,但我想在MVC4中处理IoC是不同的。 当我使用StructureMap来处理MVC4中的IoC时,我得到以下异常。:

没有为此对象定义的无参数构造函数

为什么呢? 我没有在谷歌找到任何正确的结果,除了这个:IoC Not Working In MVC4 这些是我的IoC课程:

public static class IoC {
    public static IContainer Initialize() {
        ObjectFactory.Initialize(x =>
                    {
                        x.Scan(scan =>
                        {
                            //scan.Assembly("DLL.Core");
                            scan.Assembly("DLL.CMS");
                            scan.TheCallingAssembly();
                            scan.WithDefaultConventions();
                        });
                        x.For<IDbContext>().Use<ModelEntities>();
                        x.For(typeof(IRepository<>)).Use(typeof(Repository<>));
                        x.For<IHttpControllerActivator>();
                        x.For<IController>();
                    });

        return ObjectFactory.Container;
    }

SmDependencyResolver是:

    public class SmDependencyResolver : IDependencyResolver
{
    private readonly IContainer _container;

    public SmDependencyResolver(IContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType == null) return null;
        try
        {
            return serviceType.IsAbstract || serviceType.IsInterface
                     ? _container.TryGetInstance(serviceType)
                     : _container.GetInstance(serviceType);
        }
        catch
        {

            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.GetAllInstances(serviceType).Cast<object>();
    }
}

我的错误是:

  

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

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
     

来源错误:

     

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

     

堆栈追踪:

     

[MissingMethodException:没有为此定义无参数构造函数   对象。] System.RuntimeTypeHandle.CreateInstance(RuntimeType类型,   Boolean publicOnly,Boolean noCheck,Boolean&amp; canBeCached,   RuntimeMethodHandleInternal&安培; ctor,布尔&amp; bNeedSecurityCheck)+0
  System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean   skipCheckThis,Boolean fillCache)+98
  System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,   Boolean skipVisibilityChecks,Boolean skipCheckThis,Boolean   fillCache)+241 System.Activator.CreateInstance(Type type,Boolean   nonPublic)+69
  System.Web.Mvc.DefaultControllerActivator.Create(的RequestContext   requestContext,Type controllerType)+67

     

[InvalidOperationException:尝试创建时出错   控制器类型   'Parsian.Web.Areas.Dashboard.Controllers.MemberController'。确保   控制器有一个无参数的公共构造函数。]
  System.Web.Mvc.DefaultControllerActivator.Create(的RequestContext   requestContext,Type controllerType)+182
  System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(的RequestContext   requestContext,Type controllerType)+80
  System.Web.Mvc.DefaultControllerFactory.CreateController(的RequestContext   requestContext,String controllerName)+74
  System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase   httpContext,IController&amp;控制器,IControllerFactory&amp;厂)   +196 System.Web.Mvc。&lt;&gt; c__DisplayClass6.b__2()+49 System.Web.Mvc。&lt;&gt; c__DisplayClassb 1.<ProcessInApplicationTrust>b__a() +13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func
1 func)   +124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,AsyncCallback回调,对象状态)+98
  System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,   AsyncCallback回调,对象状态)+50
  System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext的   context,AsyncCallback cb,Object extraData)+16
  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()   +8862676 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+184

感谢您的正确答案。

4 个答案:

答案 0 :(得分:9)

ooops。我找到了一个紧急解决方案:)尝试从IControllerActivator实现一个类

   public class StructureMapControllerActivator : IControllerActivator
    {
        private IContainer _container;

        public StructureMapControllerActivator(IContainer container)
        {
            _container = container;
        }

        public IController Create(RequestContext requestContext, Type controllerType)
        {
            return _container.GetInstance(controllerType) as IController;
        }
}

然后将其注册到IoC类:

 x.For<IControllerActivator>().Use<StructureMapControllerActivator>();

然后享受它。 祝你好运

答案 1 :(得分:3)

如果删除structmap的旧配置并安装structurmap.mvc4 from nuget然后配置您的IoC容器,则没有任何问题。

答案 2 :(得分:2)

尝试将此类添加为您的ControllerFactory,我实际上已经在MVC3中看到了上面的错误,这通常会为我修复它

public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        try
        {
            return (controllerType == null)
                       ? base.GetControllerInstance(requestContext, controllerType)
                       : ObjectFactory.GetInstance(controllerType) as IController;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

答案 3 :(得分:0)

使用StructureMap.MVC5.Update我必须这样做,否则嵌套的IContainer已经处理好了(很奇怪):

public class StructureMapControllerActivator : IControllerActivator
{
    public IController Create(RequestContext requestContext, Type controllerType)
    {
        return StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IController;
    }
}