如何配置 StructureMap 以创建 DbConnection

How do I configue StructureMap to create a DbConnection

我的 Entity Framework 上下文有下面的代码。

我正在使用重载构造函数注入内存数据库进行测试。这很好用,但是当我在我的 MVC 应用程序中使用它时,我需要为 DbConnection 配置 StructureMap。我不知道该怎么做

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

您应该告诉 StructureMap 您要使用哪个 EfContext 构造函数。默认情况下,StructureMap 将使用最贪婪的构造函数,即具有最多参数的构造函数,在您的情况下 public EfContext(DbConnection connection)。所以在运行时,你想要指定构造函数 public EfContext(),它将从连接字符串创建 DbConnection

config.For<EfContext>().Use<EfContext>().SelectConstructor(() => new EfContext());

顺便说一句,ObjectFactory 的使用已被弃用,强烈建议不要使用它。有关在 ASP.NET Mvc 应用程序中设置 StructureMap 的推荐方法,请参阅 http://structuremap.github.io/integrations/aspnet-mvc/

编辑:使用正确的 SelectConstructor 语法,因为我忘记了...