asp.net-mvc-3 - 使用 Unity 容器时,没有为此对象定义无参数构造函数异常

标签 asp.net-mvc-3 c#-4.0 unity-container ioc-container

我在尝试加载 View 时遇到上述异常。

我正在使用 Unity 来初始化我的 Controller 实例。仍然出现上述错误。

这是我的 Controller 。

public class SiteController : Controller
{

    private ISiteRepository _repository;

    public SiteController(ISiteRepository repository)
    {
        _repository = repository;
    }

    //
    // GET: /Site/

    public ActionResult Index()
    {
        return View();
    }

    //
    // GET: /Site/Details/5

    public ActionResult Details(int id)
    {
        return View();
    }}

这是我的 Global.asax.cs

protected void Application_Start()
    {
        ConfigApi(GlobalConfiguration.Configuration);
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    static void ConfigApi(HttpConfiguration config)
    {
        var unity = new UnityContainer();
        unity.RegisterType<SiteController>();
        unity.RegisterType<ISiteRepository, SiteRepository>(new HierarchicalLifetimeManager());

        config.DependencyResolver = new IocContainer(unity);
    }

这是我的 SiteRepository 类。

public class SiteRepository:ISiteRepository
{
    private readonly SampleMVCEntities _dbContext;

    public SiteRepository()
    {
        _dbContext = new SampleMVCEntities();
    }

    private IQueryable<SiteConfig> MapSiteConfig()
    {
        return _dbContext.SiteConfigs.Select(a => new SiteConfig
        {
            Name = a.Name,
            LinkColour = a.LinkColour,
            SiteLogo = a.SiteLogo,
            SiteBrands = a.SiteBrands.Select(b => new Models.SiteBrand { SiteId = b.SiteId, BrandId = b.BrandId })
        });
    }

    public IEnumerable<SiteConfig> GetAll()
    {
        return MapSiteConfig().AsEnumerable();
    }}

这是我的错误堆栈。

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

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

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +114
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55

[InvalidOperationException: An error occurred when trying to create a controller of type 'Config.Controllers.SiteController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +179
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& controller, IControllerFactory& factory) +197 System.Web.Mvc.<>c_DisplayClass6.b_2() +49 System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a() +13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22<br/> System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func1 func) +88 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +268 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

<小时/>

有人可以帮助我吗?

谢谢。

最佳答案

ASP.NET MVC 和 ASP.NET Web API 使用两个独立的依赖关系解析器

对于从 Controller 派生的“常规”MVC Controller ,您需要使用 DependencyResolver.SetResolver:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

对于从 ApiController 派生的 Wep API Controller ,您需要在代码中使用 GlobalConfiguration.Configuration.DependencyResolver

因此,如果您计划使用这两种类型的 Controller ,则需要注册容器两次。

有一篇很好的文章如何为两个依赖解析器设置 Unity:

Dependency Injection in ASP.NET MVC 4 and WebAPI using Unity

关于asp.net-mvc-3 - 使用 Unity 容器时,没有为此对象定义无参数构造函数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905381/

相关文章:

c# - 在 C# MVC3 中缓存 JSON 数据

unit-testing - TestMethod Visual Studio 2010上的ExpectedException

wpf - 我如何松散地引用 Prism 中的模块,以便它们可以存在或不存在?

c# - 依赖注入(inject)的实现

wpf - Unity 的嵌套数据上下文

asp.net-mvc-3 - Adam Freeman 书中的 Pro.ASP.NET.MVC.3.Framework 中的错误

asp.net-mvc - ASP.NET MVC 4 - 嵌套模型 - 如何设置正确的关联?

asp.net - 如何将 ItemTemplate 文本值设置为组合框 DataTextField 而不是 DataValueField

c# - Ninject 对 MVC3 中 Action 方法参数的依赖注入(inject)

c# - 如何防止输出参数以 WCF Web 服务中的返回参数结束?