C# ASP.NETMVC-“;无法创建接口的实例";

C# ASP.NETMVC-“;无法创建接口的实例";,c#,exception,asp.net-mvc-3,asp.net-mvc-routing,C#,Exception,Asp.net Mvc 3,Asp.net Mvc Routing,我试图解决这个问题已经有一段时间了,但我已经走到了死胡同,也许你们可以帮我。请注意,这与此问题无关 我首先在MVC3中使用实体代码。我一定对我的一个对象做了一些狡猾的事情,因为当它第一次尝试创建数据库并从我的Seed函数填充它时,会发生此错误(实际上从未调用Seed函数,但创建了数据库和表) 异常会在系统的深处引发: > mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool skipCheckT

我试图解决这个问题已经有一段时间了,但我已经走到了死胡同,也许你们可以帮我。请注意,这与此问题无关

我首先在MVC3中使用实体代码。我一定对我的一个对象做了一些狡猾的事情,因为当它第一次尝试创建数据库并从我的
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]  
这是我的
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
你可能需要或不需要更多的信息,我将提供它显然。我不知道从哪里开始找。该错误甚至可能与我的模型无关,但无论如何。我注意到它发生在MvcRouteHandler中,我在这里没有做任何特殊的事情,如果我忽略了异常,我将在HomeController的操作处理程序中结束。我在这里得到一个错误,因为数据库没有种子(因为从未调用
Seed

哦,如果有帮助的话,
global.asax.cs
中的初始值设定项:

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

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
受保护的无效应用程序\u Start()
{
DbDatabase.SetInitializer(新的ModelInitializer());
RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
注册地址(RouteTable.Routes);
}
任何帮助或指点都将不胜感激

编辑:控制器如下所示:

    public ActionResult Index()
    {
        Models.CMS.CategoryRepository repo = Models.CMS.CategoryRepository.Instance;
        List<Models.CMS.Category> cats = repo.GetAll();
        return View();
    }
public interface ICategoryRepository
{
    void Add(Category category);
    void Remove(Category category);
    List<Category> GetAll(int parentId = 0);
    Category GetRoot();
    Category Get(int id);
}
public class CategoryRepository : ICategoryRepository
{
    private readonly ModelContext context;

    // Here we pass in the context so that it can be used by methods.
    public CategoryRepository(ModelContext context)
    {
        this.context = context;
    }

    #region ICategoryRepository Members

    public void Add(Category category, Category parent = null)
    {

        if (parent == null)
        {
            parent = this.GetRoot();
        }
        // Snipped the stuff here.

        // Finally add to the current context.
        this.context.ContentCategories.Add(category);
    }

    // And all other methods...
}
public ActionResult Index()
{
Models.CMS.CategoryRepository repo=Models.CMS.CategoryRepository.Instance;
List cats=repo.GetAll();
返回视图();
}

但是,该错误在到达该处理程序之前发生。
GetAll()
调用中的某些代码会出现错误,因为数据库未填充(从未调用初始值设定项)。

我下载了该项目。首先,为了不出现任何模型问题而从头开始,我将
模型初始值设定项设置为从
DropCreateDatabaseAlways
继承,因为我不希望每次调试时数据库中有任何过时的数据

当我运行应用程序时,我在
CategoryRepository
Add()
方法中得到一个空异常。我认为您可能对存储库模式有误解。目前,您使用的是静态存储库,IMO不适合这样做。您还将在多个位置创建一个新的模型上下文,您应该通过将其作为参数传递到存储库来避免这种情况。理想情况下,类别存储库的界面应如下所示:

    public ActionResult Index()
    {
        Models.CMS.CategoryRepository repo = Models.CMS.CategoryRepository.Instance;
        List<Models.CMS.Category> cats = repo.GetAll();
        return View();
    }
public interface ICategoryRepository
{
    void Add(Category category);
    void Remove(Category category);
    List<Category> GetAll(int parentId = 0);
    Category GetRoot();
    Category Get(int id);
}
public class CategoryRepository : ICategoryRepository
{
    private readonly ModelContext context;

    // Here we pass in the context so that it can be used by methods.
    public CategoryRepository(ModelContext context)
    {
        this.context = context;
    }

    #region ICategoryRepository Members

    public void Add(Category category, Category parent = null)
    {

        if (parent == null)
        {
            parent = this.GetRoot();
        }
        // Snipped the stuff here.

        // Finally add to the current context.
        this.context.ContentCategories.Add(category);
    }

    // And all other methods...
}

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

动作/控制器是什么样子的?你什么时候会收到这个错误?@Filip Ekberg,谢谢你的回复。我对其进行了编辑,以包含控制器方法。错误发生在它点击此方法之前。@Moo Juice,如果您在global.asax.cs中的
应用程序\u Start
的第一行设置断点,它是否通过
设置初始值设定项
行?@Filip Ekberg,是的。顺便说一句,在此之前,我得到了一个“未找到文化”异常,但不确定这是否相关。我跳过了
SetInitializer
行,很好。你能添加你的控制器构造函数吗?看起来您正在向构造函数传递一个接口,而默认依赖项解析程序正在尝试实例化它,但这显然是不可能的。感谢您对这个问题的承诺。由于之前发生的错误,我从未像Add()方法那样深入。您能告诉我为什么静态存储库是一个如此糟糕的主意,为什么在中传递上下文是值得的吗?再次感谢您花时间看这个。@Moo-没问题。拥有静态存储库和硬编码上下文会增加耦合,并消除测试代码的任何可能性。另外,为web项目保留静态对象是错误的。“工作单元”正是EF-CF中的“上下文”所在。在web中,每个请求通常只有一个工作单元(也称为上下文)。因此,在操作中创建它们比“更深入”(如存储库)要好得多。您不应该将存储库看作是可以查询和执行操作的内存中列表。它应该只与UoW一起工作,而不是保存它。(续)因此,理想情况下,您应该使用依赖注入框架,如Ninject、AutoFac或Castle Windsor,并将它们“注入”到控制器的构造函数中。也许这对你现在来说有点困难。拥有一个“工作单元”的想法本质上就像一个数据库事务——做一堆事情,然后保存更改()(在控制器的操作中)。希望这有助于更好地解释问题。@TheCloudlessky,谢谢你的建议,但是如何在没有静态数据的情况下正确地缓存东西呢?您是否将东西放入会话或应用程序对象中?例如,在我的“Category”存储库中,它缓存根注释,因为它将被频繁访问。事实上,在其他领域,缓存其他东西是有意义的。因此,在这些情况下,是否最好将非静态对象包装在其他对象周围?在web意义上,您可以在HttpContext上使用Cache属性。在您的例子中,您可以完全像以前一样使用root,但不要使任何东西成为静态的。因此,您需要新建存储库,然后在调用Root时,它将查询当前上下文并将其存储在实例变量中。您不需要通过将对象缓存到