AutoFac DbContext问题 - 在模型创建时无法使用

时间:2013-03-15 11:16:37

标签: c# dependency-injection inversion-of-control servicestack autofac

我在使用AutoFac和IoC时遇到了一些问题。我们已经有了一个有效的应用程序,但是我从头开始使用这个应用程序并且看不出两者之间的区别在哪里。

我正在使用一个简单的AJAX页面测试它,该页面通过ServiceStack API调用服务层。当使用MockRepositories时,这很好用,所以我知道事情的一面是有效的。

然而,当我用使用Entity Framework的模拟替换模拟时,尽管所有注册看起来都是正确且有效的,但我得到错误“在创建模型时不能使用上下文。”

我在下面提供了我的代码:

public class SomeObject
{
    public int Id { get; set; }
}



public class IoCExampleContext : DbContext, IIoCExampleContext
{

    public IDbSet<SomeObject> SomeObjects { get; set; }

    static IoCExampleContext()
    {
        Database.SetInitializer(new IoCExampleDatabaseInitilizer());
    }

    public IoCExampleContext(string connectionStringName)
        : base(connectionStringName)
    {
        Configuration.ProxyCreationEnabled = false;
    }

    public IoCExampleContext()
        : this("name=IoCExample")
    {}


    public string ConnectionString
    {
        get { return Database.Connection.ConnectionString; }
    }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        BuildModels(modelBuilder);
    }

    private void BuildModels(DbModelBuilder builder)
    {
        var typeToUse = typeof(SomeObjectModelBuilder);
        var namespaceToUse = typeToUse.Namespace;

        var toReg = Assembly
                        .GetAssembly(typeToUse)
                        .GetTypes()
                        .Where(type => type.Namespace != null && type.Namespace.StartsWith(namespaceToUse))
                        .Where(type => type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

        foreach (object configurationInstance in toReg.Select(Activator.CreateInstance))
        {
            builder.Configurations.Add((dynamic)configurationInstance);
        }
    }
}



public class IoCExampleDatabaseInitilizer : CreateDatabaseIfNotExists<IoCExampleContext>
{
    protected override void Seed(IoCExampleContext context)
    {
    }
}



public interface IRepository<TEntity> where TEntity : class
{
    IQueryable<TEntity> GetQuery();
    IEnumerable<TEntity> GetAll();
    IEnumerable<TEntity> Where(Expression<Func<TEntity, bool>> predicate);

    // ...Various "standard" CRUD calls
}



public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected DbContext _context;
    private readonly DbSet<TEntity> _dbSet;

    public GenericRepository(DbContext context)
    {
        _context = context;
        _dbSet = _context.Set<TEntity>();
    }

    public IQueryable<TEntity> GetQuery()
    {
        return _dbSet;
    }

    public IEnumerable<TEntity> GetAll()
    {
        return GetQuery().AsEnumerable();
    }

    public IEnumerable<TEntity> Where(Expression<Func<TEntity, bool>> predicate)
    {
        return GetQuery().Where(predicate);
    }

    // ...Various "standard" CRUD calls

    public void Dispose()
    {
        OnDispose(true);
    }

    protected void OnDispose(bool disposing)
    {
        if (disposing)
        {
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
    }
}


public class DependencyBootstrapper
{
    private ContainerBuilder _builder;

    public IContainer Start()
    {
        _builder = new ContainerBuilder();
        _builder.RegisterFilterProvider();
        RegisterControllers();
        return _builder.Build();
    }

    private void RegisterControllers()
    {
        RegisterAssembly(Assembly.GetExecutingAssembly());
        _builder.RegisterModelBinderProvider();

        RegisterPerLifetimeConnections();
        RegisterRepositories();
        RegisterServices();
    }

    private void RegisterAssembly(Assembly assembly)
    {
        _builder.RegisterModelBinders(assembly);
        _builder.RegisterControllers(assembly);
    }

    private void RegisterRepositories()
    {
        _builder.RegisterGeneric(typeof(GenericRepository<>)).As(typeof(IRepository<>)); 
        _builder.RegisterType<GenericRepository<SomeObject>>().As<IRepository<SomeObject>>();
        //... More registrations
    }

    private void RegisterServices()
    {
        _builder.RegisterType<SomeObjectService>().As<ISomeObjectService>();
        //... More registrations
    }

    private void RegisterPerLifetimeConnections()
    {
        const string connectionStringName = "IoCExample";
        _builder.RegisterType<IoCExampleContext>()
            .As<DbContext>()
            .WithParameter("connectionStringName", connectionStringName)
            .InstancePerLifetimeScope();

        _builder.Register(c => new HttpContextWrapper(HttpContext.Current))
            .As<HttpContextBase>();
    }
}

我不知道它是否相关但由于我们无法访问global.asax方法,我们通过PreApplicationStartMethod.OnPreApplicationStart调用引导程序(据我所知,这几乎是与Application_Start相同的事情。

有点担心的是,当我在连接字符串上启用多个活动结果集时,它会起作用 - 这会告诉我我正在正确注册DbContext并且它跨越多个上下文。

有人能找到我错的地方吗?

1 个答案:

答案 0 :(得分:0)

连接字符串是个问题。确保您已在web / app.com中正确设置。