C# AutoFac DbContext问题-在创建模型时无法使用
在开始使用AutoFac和IoC时,我遇到了一些问题。我们有一个正常工作的应用程序,但是,我从零开始使用这个应用程序,看不出两者之间的区别 我正在用一个简单的AJAX页面测试这一点,该页面通过ServiceStackAPI调用服务层。当使用MockRepositories时,这很好,所以我知道事情的另一面正在起作用 然而,当我将mock替换为使用实体框架的mock时,尽管所有的注册看起来都是正确的和有效的,但我得到了错误“在创建模型时无法使用上下文” 我已将我的代码包括在下面:C# AutoFac DbContext问题-在创建模型时无法使用,c#,dependency-injection,inversion-of-control,servicestack,autofac,C#,Dependency Injection,Inversion Of Control,servicestack,Autofac,在开始使用AutoFac和IoC时,我遇到了一些问题。我们有一个正常工作的应用程序,但是,我从零开始使用这个应用程序,看不出两者之间的区别 我正在用一个简单的AJAX页面测试这一点,该页面通过ServiceStackAPI调用服务层。当使用MockRepositories时,这很好,所以我知道事情的另一面正在起作用 然而,当我将mock替换为使用实体框架的mock时,尽管所有的注册看起来都是正确的和有效的,但我得到了错误“在创建模型时无法使用上下文” 我已将我的代码包括在下面: public c
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>();
}
}
公共类SomeObject
{
公共int Id{get;set;}
}
公共类IoCExampleContext:DbContext,IIoCExampleContext
{
公共IDbSet SomeObjects{get;set;}
静态IoCExampleContext()
{
SetInitializer(新的IoCExampleDatabaseInitilizer());
}
公共IoCExampleContext(字符串连接字符串名称)
:基础(连接字符串名称)
{
Configuration.ProxyCreationEnabled=false;
}
公共IoCExampleContext()
:此(“name=IoCExample”)
{}
公共字符串连接字符串
{
获取{return Database.Connection.ConnectionString;}
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
BuildModels(modelBuilder);
}
专用void BuildModels(DbModelBuilder builder)
{
var typeToUse=typeof(SomeObjectModelBuilder);
var namespaceToUse=typeToUse.Namespace;
var toReg=组件
.GetAssembly(typeToUse)
.GetTypes()
.Where(type=>type.Namespace!=null&&type.Namespace.StartsWith(namespaceToUse))
.Where(type=>type.BaseType.IsGenericType&&type.BaseType.GetGenericTypeDefinition()==typeof(EntityTypeConfiguration));
foreach(toReg.Select(Activator.CreateInstance)中的对象配置实例)
{
builder.Configurations.Add((动态)configurationInstance);
}
}
}
公共类IoCExampleDatabaseInitilizer:CreateDatabaseIfNotExists
{
受保护的覆盖无效种子(IoCExampleContext上下文)
{
}
}
公共接口假定,其中tenty:类
{
IQueryable GetQuery();
IEnumerable GetAll();
IEnumerable Where(表达式谓词);
//…各种“标准”积垢调用
}
公共类GenericRepository:i存储,其中tenty:class
{
受保护的DbContext\u context;
私有只读数据库集_DbSet;
公共GenericRepository(DbContext上下文)
{
_上下文=上下文;
_dbSet=_context.Set();
}
公共IQueryable GetQuery()
{
返回_dbSet;
}
公共IEnumerable GetAll()
{
返回GetQuery().AsEnumerable();
}
公共IEnumerable Where(表达式谓词)
{
返回GetQuery().Where(谓词);
}
//…各种“标准”积垢调用
公共空间处置()
{
OnDispose(正确);
}
受保护的空隙(bool处理)
{
如果(处置)
{
如果(_context!=null)
{
_context.Dispose();
_上下文=空;
}
}
}
}
公共类依赖引导程序
{
私人集装箱建造商;
公共IContainer开始()
{
_builder=新的ContainerBuilder();
_builder.RegisterFilterProvider();
寄存器控制器();
返回_builder.Build();
}
专用无效注册表控制器()
{
RegisterAssembly(Assembly.getExecutionGassembly());
_RegisterModelBinderProvider();
registerLifeTimeConnections();
注册地址();
RegisterServices();
}
专用无效注册表部件(部件)
{
_建造商注册模型索引(汇编);
_建造商、注册控制器(装配);
}
私有无效注册表存储()
{
_builder.RegisterGeneric(typeof(GenericRepository)).As(typeof(IRepository));
_builder.RegisterType().As();
//…更多注册
}
私有无效注册表服务()
{
_builder.RegisterType().As();
//…更多注册
}
私有无效注册表erLifeTimeConnections()
{
常量字符串连接stringname=“IoCExample”;
_builder.RegisterType()
.As()
.WithParameter(“connectionStringName”,connectionStringName)
.InstancePerLifetimeScope();
_Register(c=>newhttpcontextwrapper(HttpContext.Current))
.As();
}
}
我不知道它是否相关,但由于我们无法访问global.asax方法,我们正在通过PreApplicationStartMethod.OnPreApplicationStart
(据我所知,这与Application\u Start差不多)
有点担心的是,当我在连接字符串上启用多个活动结果集时,它会起作用——这会向我暗示,我注册的DbContext不正确,并且它跨越了多个上下文
谁能看出我哪里做错了 连接字符串是问题所在。确保您在web/app.comfig中正确设置了它。我也面临同样的问题。你找到出路了吗?