ASP.Net MVC - “无法创建接口实例”

时间:2011-02-07 11:54:37

标签: c# exception asp.net-mvc-3 asp.net-mvc-routing

我一直试图解决这个问题一段时间了,我已经死路一条,所以也许你们可以提供帮助。请注意,这与此问题无关。

我在MVC3中使用Entity-Code First。我必须对我的一个对象做过狡猾的事情,因为当它第一次尝试创建数据库并从我的Seed函数填充它时,会发生此错误(Seed函数从未被实际调用,但是数据库和表格 >已创建)。

系统中会抛出异常:

>   mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache = true) + 0x63 bytes 
    mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic) + 0x46 bytes 
    System.Web.Mvc.dll!System.Web.Mvc.DependencyResolver.DefaultDependencyResolver.GetService(System.Type serviceType) + 0x25 bytes 
    System.Web.Mvc.dll!System.Web.Mvc.DependencyResolverExtensions.GetService<System.Web.Mvc.IControllerFactory>(System.Web.Mvc.IDependencyResolver resolver) + 0x3d bytes  
    System.Web.Mvc.dll!System.Web.Mvc.SingleServiceResolver<System.Web.Mvc.IControllerFactory>.Current.get() + 0x7e bytes   
    System.Web.Mvc.dll!System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(System.Web.Routing.RequestContext requestContext = {System.Web.Routing.RequestContext}) + 0x72 bytes  
    System.Web.Mvc.dll!System.Web.Mvc.MvcRouteHandler.GetHttpHandler(System.Web.Routing.RequestContext requestContext = {System.Web.Routing.RequestContext}) + 0x2a bytes   
    System.Web.Mvc.dll!System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(System.Web.Routing.RequestContext requestContext) + 0xb bytes 
    System.Web.dll!System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(System.Web.HttpContextBase context = {System.Web.HttpContextWrapper}) + 0x108 bytes  
    System.Web.dll!System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(object sender, System.EventArgs e) + 0x57 bytes 
    System.Web.dll!System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() + 0x95 bytes   
    System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step = {System.Web.HttpApplication.SyncEventExecutionStep}, ref bool completedSynchronously = true) + 0x4c bytes    
    System.Web.dll!System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(System.Exception error) + 0x13e bytes  
    System.Web.dll!System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext context, System.AsyncCallback cb, object extraData) + 0xad bytes  
    System.Web.dll!System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest wr = {Microsoft.VisualStudio.WebHost.Request}) + 0x1a2 bytes  
    System.Web.dll!System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest wr) + 0x7d bytes  
    System.Web.dll!System.Web.HttpRuntime.ProcessRequest(System.Web.HttpWorkerRequest wr) + 0x47 bytes  
    WebDev.WebHost40.dll!Microsoft.VisualStudio.WebHost.Request.Process() + 0x17b bytes 
    WebDev.WebHost40.dll!Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Microsoft.VisualStudio.WebHost.Connection conn = {System.Runtime.Remoting.Proxies.__TransparentProxy}) + 0x6c bytes 
    [Appdomain Transition]  
    WebDev.WebHost40.dll!Microsoft.VisualStudio.WebHost.Server.OnSocketAccept(object acceptedSocket) + 0x83 bytes   
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(object state) + 0x2d bytes 
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool ignoreSyncCtx) + 0xb0 bytes    
    mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x5a bytes 
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x147 bytes  
    mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() + 0x2d bytes    
    [Native to Managed Transition]  

此刻我只有一个对象。请注意,正如我之前所说,在数据库中创建了

// class Category
public class Category
{
    [Key]
    public int CategoryID { get; set; }

    [Required]
    [StringLength(64)]
    public string Name { get; set; }

    public int? ParentCategoryID { get; set; }
    [ForeignKey("ParentCategoryID")]
    public Category ParentCategory { get; set; }

    [Required]
    public int ListOrder { get; set; }

    // left/right
    public int TreeLeft { get; set; }
    public int TreeRight { get; set; }
}   // eo class Category

这是我的DbContext派生类:

// class ModelContext
public class ModelContext : DbContext
{
    public DbSet<Models.CMS.Category> ContentCategories { get; set; }

    // property to get the object context
    public ObjectContext ObjectContext
    {
        get
        {
            return ((IObjectContextAdapter)this).ObjectContext;
        }
    }


    // OnModelCreating
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }   // eo OnModelCreating

}   // eo class ModelContext

没有那么多。最后,我的初始化程序。永远不会调用Seed函数:

// class ModelInitializer
public class ModelInitializer : DropCreateDatabaseIfModelChanges<ModelContext>
{
    // seed
    protected override void Seed(ModelContext context)
    {
        var catRepo = Models.CMS.CategoryRepository.Instance;

        // Root category node
        context.ContentCategories.Add(catRepo.CreateRoot());

        // Test data
        Category home = catRepo.Add(new Category { Name = "Home", ListOrder = 10 });
        Category news = catRepo.Add(new Category { Name = "News", ListOrder = 20 });

        catRepo.Add(new Category { Name = "Current News", ListOrder = 10 }, news);
        catRepo.Add(new Category { Name = "Older News", ListOrder = 20 }, news);
    }   // eo Seed

}   // eo class ModelInitializer

您可能需要或不需要更多信息,我会明确提供。我不知道从哪里开始看。该错误甚至可能与我的模型无关,但无论如何。我注意它发生在MvcRouteHandler中,我没有做任何特别的事情,如果我忽略异常,我最终会在HomeController的动作处理程序中。我在这里收到错误,因为数据库没有播种(因为Seed从未被调用过)。

哦,如果它有帮助,global.asax.cs中的初始化程序:

    protected void Application_Start()
    {
        DbDatabase.SetInitializer<ModelContext>(new ModelInitializer());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

任何帮助或指示都将不胜感激!

编辑:控制器看起来像这样:

    public ActionResult Index()
    {
        Models.CMS.CategoryRepository repo = Models.CMS.CategoryRepository.Instance;
        List<Models.CMS.Category> cats = repo.GetAll();
        return View();
    }

然而,错误发生在之前到达此处理程序。然后,GetAll()调用中的某些代码会收到错误,因为未填充数据库(从未调用过初始化程序)。

1 个答案:

答案 0 :(得分:1)

我下载了这个项目。首先,为了在没有任何模型问题的情况下重新开始,我将ModelInitializer设置为继承自DropCreateDatabaseAlways,因为每次调试时我都不希望数据库中存在任何陈旧数据。

当我运行应用程序时,我在Add()的{​​{1}}方法中获得了一个空例外。我想你可能对存储库模式有误解。目前,您正在使用静态存储库,IMO很难做到这一点。您还在几个地方创建了一个新的模型上下文,您应该通过将其作为参数传递到存储库来避免。理想情况下,类别存储库的界面应如下所示:

CategoryRepository

然后在您的存储库实现内部将是这样的:

public interface ICategoryRepository
{
    void Add(Category category);
    void Remove(Category category);
    List<Category> GetAll(int parentId = 0);
    Category GetRoot();
    Category Get(int id);
}

我对项目进行了一些重大更改,所以我希望它们对存储库模式有意义。你可以找到updated project here。在我改变了这个之后,我得到了一个关于关系的例外 - 所以我认为你最好的解释是如何尝试对类别进行建模(某种形式的树结构......),我可以从那里帮助你。此外,请务必清理项目并确保数据库为空。干杯!