gpt4 book ai didi

c# - ASP.Net MVC - "Cannot Create Instance of an Interface"

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:28 25 4
gpt4 key购买 nike

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

我在 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);
}

如有任何帮助或指点,我们将不胜感激!

编辑: Controller 看起来像这样:

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

但是,错误发生在它到达此处理程序之前。该 GetAll() 调用中的某些代码随后会出错,因为数据库未填充(从未调用 Initializer)。

最佳答案

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

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

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...
}

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

关于c# - ASP.Net MVC - "Cannot Create Instance of an Interface",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4921006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com