![](/img/trans.png)
[英]How to create a DbDataAdapter given a DbCommand or DbConnection?
[英]How do I configue StructureMap to create a DbConnection
我的實體框架上下文具有以下代碼。
我正在使用重載的構造函數將其插入內存數據庫中進行測試。 這工作正常,但是當我在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()
,它將從連接public EfContext()
創建DbConnection
:
config.For<EfContext>().Use<EfContext>().SelectConstructor(() => new EfContext());
ObjectFactory
,不建議使用ObjectFactory
,強烈建議不要使用它。 有關在ASP.NET Mvc應用程序中設置StructureMap的推薦方法,請參見http://structuremap.github.io/integrations/aspnet-mvc/ 。
編輯:使用正確的SelectConstructor
語法,因為我忘記了...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.