我不确定标题是否正确描述了我的问题。如果有人可以通过阅读以下描述更好地描述我的问题,请通过将标题编辑为更有意义的内容来帮助我。
我正在尝试使用 Entity Framework 和 Ninject 学习 asp.net MVC。我正在查看 GitHub 上的 NuGet Gallery 应用程序,并尝试在我的项目中实现一些部分。
我按照这个问题中提供的答案[如何使用 EF 构建 ASP.Net MVC 应用程序?]并使用以下分层结构设计了我的项目。
我的演示应用
- MyDemoApp.Domain(包含 POCO 类)
- MyDomain.Service(包含对 Domain、EF 的引用。它仅包含接口)
- MyDemoApp.Data(包含对 EF、Domain、Service 的引用。它包含处理实体上下文和存储库的类)
- MyDemoApp.Web(包含对 ApplicationModel、Data、Domain、Service、Ninject 的引用)
- MyDemoApp.ApplicationModel(包含对数据、域、服务的引用。它实现了服务项目中的类)
MyDemoApp.Web
没有业务逻辑并且表现得像Humble Object,如this answer中所述
我在 MyDemoApp.Service 项目中有一个接口 IConfiguration,它由位于 MyDemoApp.Web 中的 Configuration 类实现,我正在尝试读取连接字符串。我需要将此连接字符串传递给在位于 MydemoApp.Data 的 EntityContextFactory 中创建的 EntityContext 对象如果我将 MyDemoApp.web 的项目引用添加到 MyDemoApp.Data 然后 Visual Studio 提示我说它会导致循环引用
在下面的代码中return new EntitiesContext("");
,我应该如何在这里传递一个参数来获取我的 bindings.cs 获取的连接字符串?
namespace MyDemoApp.Data
{
public class EntitiesContextFactory : IDbContextFactory<EntitiesContext>
{
public EntitiesContext Create()
{
//TO-DO : Get the Connnectionstring
return new EntitiesContext(""); //Need to pass connection string by calling property from Configuration class in MyDemoApp.Web project
}
}
public class EntitiesContext:DbContext,IEntitiesContext
{
public EntitiesContext(string connectionString) : base(connectionString)
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Provide mapping like foreign key
}
}
}
}
Configuration.cs
:
namespace MydemoApp.Web
{
public class Configuration : IConfiguration
{
public string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings['dev'].ConnectionString;
}
}
}
}
Bindings.cs
:
namespace MydemoApp.Web.Bindings
{
public class MyModule : NinjectModule
{
public override void Load()
{
Bind<IConfiguration>().To<Configuration>();
var configuration = new Configuration(); //Gives me Connectionstring
Bind<IEntitiesContext>().ToMethod(context => new EntitiesContext(configuration.ConnectionString)); // This part would help me pass the connection string to the constructor
}
}
}