Asp.net mvc 4 为DI包装dbContext的最佳方法是什么?

Asp.net mvc 4 为DI包装dbContext的最佳方法是什么?,asp.net-mvc-4,dependency-injection,castle-windsor,Asp.net Mvc 4,Dependency Injection,Castle Windsor,我在想,通过构造函数将dbcontext注入到我的服务层,下面这样的方法可能行得通。。。。有人有更好的方法吗? 但是,它似乎可以工作,除非我将对象强制转换为从dbcontext继承的实际类,否则_context.EntityName等不会在intellisense中显示 public interface IContextFactory:IDisposable { DbContext Create(); } public class ContextFactory<TContext&

我在想,通过构造函数将dbcontext注入到我的服务层,下面这样的方法可能行得通。。。。有人有更好的方法吗? 但是,它似乎可以工作,除非我将对象强制转换为从dbcontext继承的实际类,否则_context.EntityName等不会在intellisense中显示

 public interface IContextFactory:IDisposable
{
    DbContext Create();
}
public class ContextFactory<TContext> : IContextFactory where TContext : DbContext, new()
{
    private DbContext _context;

    public DbContext Create()
    {
        _context = new TContext();
        _context.Configuration.LazyLoadingEnabled = true;

        return _context;
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}
公共接口IContextFactory:IDisposable
{
DbContext-Create();
}
公共类ContextFactory:IContextFactory,其中TContext:DbContext,new()
{
私有DbContext _context;
公共DbContext Create()
{
_context=新的TContext();
_context.Configuration.LazyLoadingEnabled=true;
返回上下文;
}
公共空间处置()
{
_context.Dispose();
}
}

正如Steven在评论中提到的,您可以直接从合成根注入DbContext。下面是一个如何使用SimpleInjector的示例

container.Register<MyDbContext>(
    () => new MyDbContext("name=MyDbContext"),
    new WebRequestLifestyle(true));
container.Register(
()=>新的MyDbContext(“name=MyDbContext”),
新生活方式(真实);
其中MyDbContext是DbContext的子类:

public class MyDbContext: DbContext
{
    public MyDbContext(string connectionString)
        : base(connectionString)
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    /* DbSets<SomeEntity> etc */

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //etc
    }
}
公共类MyDbContext:DbContext
{
公共MyDbContext(字符串连接字符串)
:基本(连接字符串)
{
this.Configuration.LazyLoadingEnabled=true;
}
/*数据库集等*/
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
//等
}
}

这里有一个更好的主意:放弃上下文工厂,只需将
DbContext
注入构造函数。相关: