2012-08-10 24 views
9

我在trynig加載視圖時遇到了上述異常。在使用Unity容器時爲此對象異常定義的無參數構造函數

我正在使用Unity初始化我的控制器實例。仍然收到上述錯誤。

這是我的控制器。

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__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) +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


有人可以幫我嗎?

謝謝。

+0

你SiteController似乎並不有一個參數的構造函數。你嘗試過在那裏添加一個嗎? – 2012-08-10 18:23:19

+0

是的,它沒有無參數的構造函數。我正在注入依賴項,我也設置了我的自定義DependencyResolver。 – Naresh 2012-08-13 08:40:24

回答

15

ASP.NET MVC和ASP.NET Web API 使用兩個單獨的依賴關係解析器

對於「常規」 MVC控制器,它是從Controller導出您需要使用DependencyResolver.SetResolver

DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

對於WEP API控制器這是導出表格ApiController您需要使用GlobalConfiguration.Configuration.DependencyResolver在你的代碼。

所以,如果你打算使用兩種類型的控制器,你需要註冊你的容器兩次。

這是一個很好的文章如何設置統一兩個依賴解析器:

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

+0

謝謝......它正在工作 – Naresh 2012-08-13 12:07:21

相關問題