【发布时间】:2011-07-22 01:43:40
【问题描述】:
我有以下类/接口:
public interface IProjectRepository
{
IQueryably<Project> GetProjects();
}
// Depends on my EF Context
public ProjectRepository : IProjectRepository
{
private MyDbEntities context;
public ProjectRepository(MyDbEntities context)
{
this.context = context;
}
public IQueryable<Project> GetProjects()
{
return context.Projects;
}
}
我的控制器:
// Depends on IProjectRepository
public class ProjectsController : Controller
{
private IProjectRepository projectRepository;
public ProjectsController(IProjectRepository projectRepository)
{
this.projectRepository = projectRepository;
}
public ActionResult Index()
{
return View(projectRepository.GetProjects());
}
}
我需要设置我的依赖注入,以便它将 ProjectRepository 传递到我的控制器中并且它需要将我的实体框架上下文传递到项目存储库中。我需要将实体上下文设置为 HTTP 请求范围。
我不确定应该将所有映射代码放在哪里以使依赖注入工作。我也不明白如果没有默认构造函数,MVC 将如何工作。
有人可以帮我把所有的部分放在一起吗?我正在使用 StructureMap,但我可以轻松切换到其他东西,因为我不知道自己在做什么。
【问题讨论】:
-
你运行的是什么版本的 MVC?
-
如果您使用的是 ASP.NET MVC 3,您应该真正利用它内置在
DependencyResolver中的优势。有关更多信息,请参阅我的答案。 -
我注意到 DependencyResolver 有问题。 MVC3的IDependencyResolver接口有个大问题:没有释放方法。这意味着如果您打算将它与 Windsor 一起使用,则可能存在内存泄漏。在此处查看我的博客文章:mikehadlow.blogspot.com/2011/02/…
标签: c# asp.net-mvc dependency-injection structuremap