首先,Jeff T 在答案中提供的解决方案有效!
我将总结我为使Ninject在 ASP.NET MVC 4 + EF 5 项目中工作所采取的步骤。值得一提的是,在以下示例中,特定存储库模式是通过SharpRepository实现的。
所需软件
- 通过NuGet安装Ninject和“Ninject.MVC3”(也安装“Ninject.Web.Common”)。
- 通过NuGet安装SharpRepository、“SharpRepository for EF5”和“SharpRepository with Ninject IOC” 。
定义存储库层
创建一个DbContext 派生类,例如Domain.EfContext
。它是
“推荐的使用上下文的方式”。
为特定存储库定义一个接口,例如:
// TODO By extending IRepository, the interface implements default Create-Read-Update-Delete (CRUD) logic.
// We can use "traits" to make the repository more "specific", e.g. via extending "ICanInsert".
// https://github.com/SharpRepository/SharpRepository/blob/master/SharpRepository.Samples/HowToUseTraits.cs
public interface IProjectRepository : IRepository<Project>
{
// TODO Add domain specific logic here.
}
定义一个实现特定存储库并继承自的类SharpRepository.Repository.ConfigurationBasedRepository<T, TKey>
,例如:
public class ProductRepository : ConfigurationBasedRepository<Product, int>, IProductRepository
{
// TODO Implement domain specific logic here.
}
定义消费者层
创建一个控制器,例如Controllers.ProductController
.
public class ProductController : Controller
{
private IProductRepository Repository { get; private set; }
// TODO Will be used by the DiC.
public ProductController(IProductRepository repository)
{
this.Repository = repository;
}
}
通过依赖注入容器 (DiC) Ninject 设置依赖注入 (DI)
该文件App_Start/NinjectWebCommon.cs
由 Ninject.Web.Common 自动创建,我们可以RegisterServices(IKernel kernel) : void
在类的方法中加载我们的模块并注册我们的服务NinjectWebCommon
。以下是该示例方法的完整源代码:
private static void RegisterServices(IKernel kernel)
{
kernel.BindSharpRepository();
RepositoryDependencyResolver.SetDependencyResolver(
new NinjectDependencyResolver(kernel)
);
string connectionString = ConfigurationManager.ConnectionStrings["EfContext"].ConnectionString;
kernel.Bind<DbContext>()
.To<EfContext>()
.InRequestScope()
.WithConstructorArgument("connectionString", connectionString);
kernel.Bind<IProductRepository>().To<ProductRepository>();
}
在 中定义以下sharpRepository
部分Web.config
:
<sharpRepository>
<repositories default="ef5Repository">
<repository name="ef5Repository"
connectionString="EfContext"
cachingStrategy="standardCachingStrategy"
dbContextType="Domain.EfContext, Domain"
factory="SharpRepository.Ef5Repository.Ef5ConfigRepositoryFactory, SharpRepository.Ef5Repository"
/>
</repositories>
</sharpRepository>
此外,connectionStrings
使示例完整的部分(我使用的是 SQL Server LocalDB)。
<connectionStrings>
<add name="EfContext" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Domain;Integrated Security=True" />
</connectionStrings>
我希望这个结论可以帮助其他人将 ASP.NET MVC 4 与 Entity Framework 5 和 SharpRepository 一起启动并运行!
如果我采取了一个或多个不必要的步骤,或者如果您看到改进示例中描述的架构的可能性,请给我回复。
顺便说一句,我必须将dbContextType
属性添加到该repository
部分以使其工作(与 Jeff T 的答案相反)。
编辑(2013-08-28):删除了不必要的步骤(最新版本的 SharpRepository 不需要)。