如何配置StructureMap来创建DbConnection ?

本文关键字:创建 DbConnection StructureMap 何配置 配置 | 更新日期: 2023-09-27 17:51:17

我的实体框架上下文的代码如下:

我正在使用重载构造函数注入内存数据库进行测试。这工作得很好,但当我在我的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来创建DbConnection ?

你应该告诉StructureMap你想使用哪个EfContext构造函数。在默认情况下,StructureMap将使用最贪婪的构造函数,即具有最多参数的构造函数,在您的示例中是public EfContext(DbConnection connection)。因此,在运行时,您需要指定构造器public EfContext(),它将从connectionstring创建DbConnection:

config.For<EfContext>().Use<EfContext>().SelectConstructor(() => new EfContext());
作为题外话,不推荐使用ObjectFactory,强烈建议不要使用它。请参阅http://structuremap.github.io/integrations/aspnet-mvc/了解在ASP中设置StructureMap的推荐方法。. NET Mvc应用程序。

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