下面有我的实体框架上下文的代码。
我使用重载的构造函数注入内存数据库进行测试。这很好,但是当我在我的MVC应用程序中使用它时,我需要为StructureMap配置DbConnection。我不知道该怎么做
public class EfContext : DbContext
{
//This can be a full blown connection string or if it is just a single string like this it is defaulting to SQL Express
public EfContext() : base("SQLExpressPaxiumMusic")
{
}
public EfContext(DbConnection connection) : base(connection, true)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new DbContextInitialiser());
}
public DbSet<User> Users { get; set; }
}
public static IContainer Initialize()
{
ObjectFactory.Configure(config =>
{
config.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
config.For<IWebAuthenticator>().Use<WebAuthenticator>();
config.For<EfContext>().Use<EfContext>();
config.For<IUserRepository>().Use<UserRepository>();
config.For<DbConnection>() ****What goes here**** ????
});
return ObjectFactory.Container;
}发布于 2015-06-01 09:37:16
您应该告诉StructureMap您想使用哪个EfContext构造函数。默认情况下,StructureMap将使用最贪婪的构造函数,即参数最多的构造函数,在您的例子中是public EfContext(DbConnection connection)。因此,在运行时,您需要指定构造函数public EfContext(),它将从连接字符串创建DbConnection:
config.For<EfContext>().Use<EfContext>().SelectConstructor(() => new EfContext());顺便说一句,不推荐使用ObjectFactory,因此强烈建议不要使用它。有关在http://structuremap.github.io/integrations/aspnet-mvc/应用程序中安装StructureMap的推荐方法,请参见ASP.NET。
编辑:使用正确的SelectConstructor语法,因为我忘记.
https://stackoverflow.com/questions/30569382
复制相似问题