Autofac-DataContext不会在生命周期范围的末尾处置

时间:2019-01-30 09:50:31

标签: c# autofac unit-of-work

我有一个命令行程序,该程序将数据导入到我的系统中。因为它将数据插入许多表中,所以我需要进行更改跟踪。为了尝试防止作业随时间推移而变慢,我使用了Autofac(我的依赖项注入框架)来创建一个内部生命周期范围,从中可以解析依赖项。在每个批处理的末尾,我将重新创建生存期范围并获取依赖项的新实例。问题是,当我这样做时,UnitOfWork依赖的DataContext不会每次都刷新,从而导致作业变慢,并最终在完成之前终止。

在调试时,我可以在DbContext上设置“ Make Object ID”,例如

enter image description here

每批处理后,对象ID仍为$ 2,表明DataContext实例未获取新实例。为什么没有获得新实例?

我的代码如下所示:

foreach (var batch in data.Batch(10))
{
    using (var scope = LifetimeScope.BeginLifetimeScope(b =>
    {
        b.RegisterType<UnitOfWork>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterType<MyService1>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterType<MyService2>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterGeneric(typeof(EntityBaseRepository<>)).As(typeof(IEntityBaseRepository<>)).InstancePerLifetimeScope();
    }))
    {
        UnitOfWork = scope.Resolve<IUnitOfWork>();
        MyService1 = scope.Resolve<IMyService1>();
        MyService2 = scope.Resolve<IMyService2>();
        Thing1Repository = scope.Resolve<IEntityBaseRepository<Thing1Repository>>();
        Thing2Repository = scope.Resolve<IEntityBaseRepository<Thing2Repository>>();

        foreach (var row in batch)
        {
            try
            {
                ParseRow(row);
            }
            catch (Exception e)
            {
                JobLogger.Error(e, "Failed to parse row. Exception: " + e.Message);
                throw;
            }

        }
    }
}

据我了解,当我获得依赖项的新实例时,子依赖项也将获得新的实例吗?为什么原始DataContext仍然悬而未决?

我的UnitOfWork看起来像这样:

public class UnitOfWork : Disposable, IUnitOfWork
{
    private readonly IDbFactory _dbFactory;
    private DataContext _dbContext;

    public UnitOfWork(IDbFactory dbFactory)
    {
        _dbFactory = dbFactory;
    }

    public DataContext DbContext => _dbContext ?? (_dbContext = _dbFactory.Initialise());

    public void Commit()
    {
        DbContext.Commit();
    }
}

我的DbFactory负责创建DataContext的新实例:

public class DbFactory : Disposable, IDbFactory
{
    DataContext _dbContext;

    public DbFactory()
    {
        _dbContext = new DataContext();
    }

    public DataContext Initialise()
    {
        return _dbContext ?? (_dbContext = new DataContext());
    }

    protected override void DisposeCore()
    {
        _dbContext?.Dispose();
    }
}

在程序首次通过调用此方法启动时,通过扫描程序集来注册我的服务:

AutofacConfig.InitialiseJobRunner();

在此方法中,我这样注册我的类型:

builder.RegisterType<DataContext>().AsSelf().InstancePerMatchingLifetimeScope(lifetimeScope);
builder.RegisterGenericInstance(typeof(EntityBaseRepository<>), typeof(IEntityBaseRepository<>), lifetimeScope);
builder.RegisterAssemblyInterfaces(Assembly.Load(Data), lifetimeScope);

RegisterAssemblyInterfaces实现为:

public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
        RegisterAssemblyInterfaces(this ContainerBuilder builder, Assembly assembly, object lifetimeScope)
{
    return builder.RegisterAssemblyTypes(assembly)
        .AsImplementedInterfaces()
        .InstancePerMatchingLifetimeScope(lifetimeScope);
}

1 个答案:

答案 0 :(得分:2)

如你注册组件接口,如以下

public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
    RegisterAssemblyInterfaces(this ContainerBuilder builder, Assembly assembly, object lifetimeScope)
{
    return builder.RegisterAssemblyTypes(assembly)
        .AsImplementedInterfaces()
        .InstancePerMatchingLifetimeScope(lifetimeScope);
}

我的猜测是您的DbFactory也以这种方式注册。在这种情况下(根据https://autofac.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope),您将获得与工厂相同的实例,因为未命名子作用域。尝试添加

b.RegisterType<DbFactory>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();

在循环中或将DbFactory更改为始终在Initialize方法中返回新的上下文,而不是如果已实例化则返回相同的上下文。