主頁 > .NET開發 > [Abp vNext 原始碼分析] - 14. EntityFramework Core 的集成

[Abp vNext 原始碼分析] - 14. EntityFramework Core 的集成

2020-09-18 11:04:23 .NET開發

一、簡要介紹

在以前的文章里面,我們介紹了 ABP vNext 在 DDD 模塊定義了倉儲的介面定義和基本實作,本章將會介紹,ABP vNext 是如何將 EntityFramework Core 框架跟倉儲進行深度集成,

ABP vNext 在集成 EF Core 的時候,不只是簡單地實作了倉儲模式,除開倉儲以外,還提供了一系列的基礎設施,如領域事件的發布,資料過濾器的實作,

二、原始碼分析

EntityFrameworkCore 相關的模塊基本就下面幾個,除了第一個是核心 EntityFrameworkCore 模塊以外,其他幾個都是封裝的 EntityFrameworkCore Provider,方便各種資料庫進行集成,

2.1 EF Core 模塊集成與初始化

首先從 Volo.Abp.EntityFrameworkCoreAbpEntityFrameworkCoreModule 開始分析,該模塊只重寫了 ConfigureServices() 方法,在內部也只有兩句代碼,

public override void ConfigureServices(ServiceConfigurationContext context)
{
    // 呼叫 AbpDbContextOptions 的預配置方法,為了解決下面的問題,
    // https://stackoverflow.com/questions/55369146/eager-loading-include-with-using-uselazyloadingproxies
    Configure<AbpDbContextOptions>(options =>
    {
        options.PreConfigure(abpDbContextConfigurationContext =>
        {
            abpDbContextConfigurationContext.DbContextOptions
                .ConfigureWarnings(warnings =>
                {
                    warnings.Ignore(CoreEventId.LazyLoadOnDisposedContextWarning);
                });
        });
    });

    // 注冊 IDbContextProvider 組件,
    context.Services.TryAddTransient(typeof(IDbContextProvider<>), typeof(UnitOfWorkDbContextProvider<>));
}

首先看第一句代碼,它在內部會呼叫 AbpDbContextOptions 提供的 PreConfigure() 方法,這個方法邏輯很簡單,會將傳入的 Action<AbpDbContextConfigurationContext> 委托添加到一個 List<Action<AbpDbContextConfigurationContext>> 集合,并且在 DbContextOptionsFactory 工廠中使用,

第二局代碼則比較簡單,為 IDbContextProvider<> 型別注入默認實作 UnitOfWorkDbContextProvider<>

public class AbpDbContextOptions
{
    internal List<Action<AbpDbContextConfigurationContext>> DefaultPreConfigureActions { get; set; }

    // ...

    public void PreConfigure([NotNull] Action<AbpDbContextConfigurationContext> action)
    {
        Check.NotNull(action, nameof(action));

        DefaultPreConfigureActions.Add(action);
    }

    // ...
}


從上面的代碼可以看出來,這個 AbpDbContextConfigurationContext 就是一個配置背景關系,用于 ABP vNext 框架在初始化的時候進行各種配置,

2.1.1 EF Core Provider 的集成

在翻閱 AbpDbContextOptions 代碼的時候,我發現除了預配置方法,它還提供了一個 Configure([NotNull] Action<AbpDbContextConfigurationContext> action) 方法,以及它的泛型多載 Configure<TDbContext>([NotNull] Action<AbpDbContextConfigurationContext<TDbContext>> action),它們的內部實作與預配置類似,

這兩個方法在 ABP vNext 框架內部的應用,主要在各個 EF Provider 模塊當中有體現,

這里我以 Volo.Abp.EntityFrameworkCore.PostgreSql 模塊作為例子,在專案內部只有兩個擴展方法的定義類,在 AbpDbContextOptionsPostgreSqlExtensions 當中,就使用到了 Configure() 方法,

public static void UsePostgreSql(
    [NotNull] this AbpDbContextOptions options,
    [CanBeNull] Action<NpgsqlDbContextOptionsBuilder> postgreSqlOptionsAction = null)
{
    options.Configure(context =>
    {
        // 這里的 context 型別是 AbpDbContextConfigurationContext,
        context.UsePostgreSql(postgreSqlOptionsAction);
    });
}

上面代碼中的 UsePostgreSql() 方法很明顯不是 EF Core Provider 所定義的擴展方法,跳轉到具體實作,發現就是一層簡單的封裝,由于 AbpDbContextConfigurationContext 內部提供了 DbContextOptionsBuilder ,所以直接使用這個 DbContextOptionsBuilder 呼叫提供的擴展方法即可,

public static class AbpDbContextConfigurationContextPostgreSqlExtensions
{
    public static DbContextOptionsBuilder UsePostgreSql(
        [NotNull] this AbpDbContextConfigurationContext context,
        [CanBeNull] Action<NpgsqlDbContextOptionsBuilder> postgreSqlOptionsAction = null)
    {
        if (context.ExistingConnection != null)
        {
            return context.DbContextOptions.UseNpgsql(context.ExistingConnection, postgreSqlOptionsAction);
        }
        else
        {
            return context.DbContextOptions.UseNpgsql(context.ConnectionString, postgreSqlOptionsAction);
        }
    }
}

2.1.2 資料庫背景關系的配置工廠

無論是 PreConfigure() 的委托集合,還是 Configure() 配置的委托,都會在 DbContextOptionsFactory 提供的 Create<TDbContext>(IServiceProvider serviceProvider) 方法中被使用,該方法的作用只有一個,執行框架的配置方法,然后生成資料庫背景關系的配置物件,

internal static class DbContextOptionsFactory
{
    public static DbContextOptions<TDbContext> Create<TDbContext>(IServiceProvider serviceProvider)
        where TDbContext : AbpDbContext<TDbContext>
    {
        // 獲取一個 DbContextCreationContext 物件,
        var creationContext = GetCreationContext<TDbContext>(serviceProvider);

        // 依據 creationContext 資訊構造一個配置背景關系,
        var context = new AbpDbContextConfigurationContext<TDbContext>(
            creationContext.ConnectionString,
            serviceProvider,
            creationContext.ConnectionStringName,
            creationContext.ExistingConnection
        );

        // 獲取 AbpDbOptions 配置,
        var options = GetDbContextOptions<TDbContext>(serviceProvider);

        // 從 Options 當中獲取添加的 PreConfigure 與 Configure 委托,并執行,
        PreConfigure(options, context);
        Configure(options, context);

        // 
        return context.DbContextOptions.Options;
    }

    // ...
}

首先我們來看看 GetCreationContext<TDbContext>() 方法是如何構造一個 DbContextCreationContext 物件的,它會優先從 Current 取得一個背景關系物件,如果存在則直接回傳,不存在則使用連接字串等資訊構建一個新的背景關系物件,

private static DbContextCreationContext GetCreationContext<TDbContext>(IServiceProvider serviceProvider)
    where TDbContext : AbpDbContext<TDbContext>
{
    // 優先從一個 AsyncLocal 當中獲取,
    var context = DbContextCreationContext.Current;
    if (context != null)
    {
        return context;
    }

    // 從 TDbContext 的 ConnectionStringName 特性獲取連接字串名稱,
    var connectionStringName = ConnectionStringNameAttribute.GetConnStringName<TDbContext>();
    // 使用 IConnectionStringResolver 根據指定的名稱獲得連接字串,
    var connectionString = serviceProvider.GetRequiredService<IConnectionStringResolver>().Resolve(connectionStringName);

    // 構造一個新的 DbContextCreationContext 物件,
    return new DbContextCreationContext(
        connectionStringName,
        connectionString
    );
}

2.1.3 連接字串決議器

與老版本的 ABP 一樣,ABP vNext 將連接字串決議的作業,抽象了一個決議器,連接字串決議器默認有兩種實作,適用于普通系統和多租戶系統,

普通的決議器,名字叫做 DefaultConnectionStringResolver,它的連接字串都是從 AbpDbConnectionOptions 當中獲取的,而這個 Option 最終是從 IConfiguration 映射過來的,一般來說就是你 appsetting.json 檔案當中的連接字串配置,

多租戶決議器 的實作叫做 MultiTenantConnectionStringResolver,它的內部核心邏輯就是獲得到當前的租戶,并查詢租戶所對應的連接字串,這樣就可以實作每個租戶都擁有不同的資料庫實體,

2.1.4 資料庫背景關系配置工廠的使用

回到最開始的地方,方法 Create<TDbContext>(IServiceProvider serviceProvider) 在什么地方會被使用呢?跳轉到唯一的呼叫點是在 AbpEfCoreServiceCollectionExtensions 靜態類的內部,它提供的 AddAbpDbContext<TDbContext>() 方法內部,就使用了 Create<TDbContext>() 作為 DbContextOptions<TDbContext> 的工廠方法,

public static class AbpEfCoreServiceCollectionExtensions
{
    public static IServiceCollection AddAbpDbContext<TDbContext>(
        this IServiceCollection services, 
        Action<IAbpDbContextRegistrationOptionsBuilder> optionsBuilder = null)
        where TDbContext : AbpDbContext<TDbContext>
    {
        services.AddMemoryCache();

        // 構造一個資料庫注冊配置物件,
        var options = new AbpDbContextRegistrationOptions(typeof(TDbContext), services);
        // 回呼傳入的委托,
        optionsBuilder?.Invoke(options);

        // 注入指定 TDbContext 的 DbOptions<TDbContext> ,將會使用 Create<TDbContext> 方法進行瞬時物件構造,
        services.TryAddTransient(DbContextOptionsFactory.Create<TDbContext>);

        // 替換指定型別的 DbContext 為當前 TDbContext,
        foreach (var dbContextType in options.ReplacedDbContextTypes)
        {
            services.Replace(ServiceDescriptor.Transient(dbContextType, typeof(TDbContext)));
        }

        // 構造 EF Core 倉儲注冊器,并添加倉儲,
        new EfCoreRepositoryRegistrar(options).AddRepositories();

        return services;
    }
}

2.2 倉儲的注入與實作

關于倉儲的注入,其實在之前的文章就有講過,這里我就大概說一下情況,

在上述代碼當中,呼叫了 AddAbpDbContext<TDbContext>() 方法之后,就會通過 Repository Registrar 進行倉儲注入,

public virtual void AddRepositories()
{
    // 遍歷用戶添加的自定義倉儲,
    foreach (var customRepository in Options.CustomRepositories)
    {
        // 呼叫 AddDefaultRepository() 方法注入倉儲,
        Options.Services.AddDefaultRepository(customRepository.Key, customRepository.Value);
    }

    // 判斷是否需要注冊物體的默認倉儲,
    if (Options.RegisterDefaultRepositories)
    {
        RegisterDefaultRepositories();
    }
}

可以看到,在注入倉儲的時候,分為兩種情況,第一種是用戶的自定義倉儲,這種倉儲是通過 AddRepository() 方法添加的,添加之后將會把它的 物體型別倉儲型別 放在一個字典內部,在倉儲注冊器進行初始化的時候,就會遍歷這個字典,進行注入動作,

第二種情況則是用戶在設定了 RegisterDefaultRepositories=true 的情況下,ABP vNext 就會從資料庫背景關系的型別定義上遍歷所有物體型別,然后進行默認倉儲注冊,

具體的倉儲注冊實作:

public static IServiceCollection AddDefaultRepository(this IServiceCollection services, Type entityType, Type repositoryImplementationType)
{
    // 注冊 IReadOnlyBasicRepository<TEntity>,
    var readOnlyBasicRepositoryInterface = typeof(IReadOnlyBasicRepository<>).MakeGenericType(entityType);
    // 如果具體實作型別繼承了該介面,則進行注入,
    if (readOnlyBasicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
    {
        services.TryAddTransient(readOnlyBasicRepositoryInterface, repositoryImplementationType);

        // 注冊 IReadOnlyRepository<TEntity>,
        var readOnlyRepositoryInterface = typeof(IReadOnlyRepository<>).MakeGenericType(entityType);
        if (readOnlyRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
        {
            services.TryAddTransient(readOnlyRepositoryInterface, repositoryImplementationType);
        }

        // 注冊 IBasicRepository<TEntity>,
        var basicRepositoryInterface = typeof(IBasicRepository<>).MakeGenericType(entityType);
        if (basicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
        {
            services.TryAddTransient(basicRepositoryInterface, repositoryImplementationType);

            // 注冊 IRepository<TEntity>,
            var repositoryInterface = typeof(IRepository<>).MakeGenericType(entityType);
            if (repositoryInterface.IsAssignableFrom(repositoryImplementationType))
            {
                services.TryAddTransient(repositoryInterface, repositoryImplementationType);
            }
        }
    }

    // 獲得物體的主鍵型別,如果不存在則忽略,
    var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType);
    if (primaryKeyType != null)
    {
        // 注冊 IReadOnlyBasicRepository<TEntity, TKey>,
        var readOnlyBasicRepositoryInterfaceWithPk = typeof(IReadOnlyBasicRepository<,>).MakeGenericType(entityType, primaryKeyType);
        if (readOnlyBasicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
        {
            services.TryAddTransient(readOnlyBasicRepositoryInterfaceWithPk, repositoryImplementationType);

            // 注冊 IReadOnlyRepository<TEntity, TKey>,
            var readOnlyRepositoryInterfaceWithPk = typeof(IReadOnlyRepository<,>).MakeGenericType(entityType, primaryKeyType);
            if (readOnlyRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
            {
                services.TryAddTransient(readOnlyRepositoryInterfaceWithPk, repositoryImplementationType);
            }

            // 注冊 IBasicRepository<TEntity, TKey>,
            var basicRepositoryInterfaceWithPk = typeof(IBasicRepository<,>).MakeGenericType(entityType, primaryKeyType);
            if (basicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
            {
                services.TryAddTransient(basicRepositoryInterfaceWithPk, repositoryImplementationType);

                // 注冊 IRepository<TEntity, TKey>,
                var repositoryInterfaceWithPk = typeof(IRepository<,>).MakeGenericType(entityType, primaryKeyType);
                if (repositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
                {
                    services.TryAddTransient(repositoryInterfaceWithPk, repositoryImplementationType);
                }
            }
        }
    }

    return services;
}

回到倉儲自動注冊的地方,可以看到實作型別是由 GetDefaultRepositoryImplementationType() 方法提供的,

protected virtual void RegisterDefaultRepository(Type entityType)
{
    Options.Services.AddDefaultRepository(
        entityType,
        GetDefaultRepositoryImplementationType(entityType)
    );
}

protected virtual Type GetDefaultRepositoryImplementationType(Type entityType)
{
    var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType);

    if (primaryKeyType == null)
    {
        return Options.SpecifiedDefaultRepositoryTypes
            ? Options.DefaultRepositoryImplementationTypeWithoutKey.MakeGenericType(entityType)
            : GetRepositoryType(Options.DefaultRepositoryDbContextType, entityType);
    }

    return Options.SpecifiedDefaultRepositoryTypes
        ? Options.DefaultRepositoryImplementationType.MakeGenericType(entityType, primaryKeyType)
        : GetRepositoryType(Options.DefaultRepositoryDbContextType, entityType, primaryKeyType);
}

protected abstract Type GetRepositoryType(Type dbContextType, Type entityType);

protected abstract Type GetRepositoryType(Type dbContextType, Type entityType, Type primaryKeyType);

這里的兩個 GetRepositoryType() 都是抽象方法,具體的實作分別在 EfCoreRepositoryRegistrarMemoryDbRepositoryRegistrarMongoDbRepositoryRegistrar 的內部,這里我們只講 EF Core 相關的,

protected override Type GetRepositoryType(Type dbContextType, Type entityType)
{
    return typeof(EfCoreRepository<,>).MakeGenericType(dbContextType, entityType);
}

可以看到,在方法內部是構造了一個 EfCoreRepository 型別作為默認倉儲的實作,

2.3 資料庫背景關系提供者

在 Ef Core 倉儲的內部,需要操作資料庫時,必須要獲得一個資料庫背景關系,在倉儲內部的資料庫背景關系都是由 IDbContextProvider<TDbContext> 提供了,這個東西在 EF Core 模塊初始化的時候就已經被注冊,它的默認實作是 UnitOfWorkDbContextProvider<TDbContext>

public class EfCoreRepository<TDbContext, TEntity> : RepositoryBase<TEntity>, IEfCoreRepository<TEntity>
    where TDbContext : IEfCoreDbContext
    where TEntity : class, IEntity
{
    public virtual DbSet<TEntity> DbSet => DbContext.Set<TEntity>();

    DbContext IEfCoreRepository<TEntity>.DbContext => DbContext.As<DbContext>();

    protected virtual TDbContext DbContext => _dbContextProvider.GetDbContext();

    // ...
    
    private readonly IDbContextProvider<TDbContext> _dbContextProvider;

    // ...

    public EfCoreRepository(IDbContextProvider<TDbContext> dbContextProvider)
    {
        _dbContextProvider = dbContextProvider;
        
        // ...
    }

    // ...
}

首先來看一下這個實作類的基本定義,比較簡單,注入了兩個介面,分別用于獲取作業單元和構造 DbContext,需要注意的是,這里通過 where 約束來指定 TDbContext 必須實作 IEfCoreDbContext 介面,

public class UnitOfWorkDbContextProvider<TDbContext> : IDbContextProvider<TDbContext>
    where TDbContext : IEfCoreDbContext
{
    private readonly IUnitOfWorkManager _unitOfWorkManager;
    private readonly IConnectionStringResolver _connectionStringResolver;

    public UnitOfWorkDbContextProvider(
        IUnitOfWorkManager unitOfWorkManager,
        IConnectionStringResolver connectionStringResolver)
    {
        _unitOfWorkManager = unitOfWorkManager;
        _connectionStringResolver = connectionStringResolver;
    }

    // ...
}

接著想下看,介面只定義了一個方法,就是 GetDbContext(),在這個默認實作里面,首先會從快取里面獲取資料庫背景關系,如果沒有獲取到,則創建一個新的資料庫背景關系,

public TDbContext GetDbContext()
{
    // 獲得當前的可用作業單元,
    var unitOfWork = _unitOfWorkManager.Current;
    if (unitOfWork == null)
    {
        throw new AbpException("A DbContext can only be created inside a unit of work!");
    }

    // 獲得資料庫連接背景關系的連接字串名稱,
    var connectionStringName = ConnectionStringNameAttribute.GetConnStringName<TDbContext>();
    // 根據名稱決議具體的連接字串,
    var connectionString = _connectionStringResolver.Resolve(connectionStringName);

    // 構造資料庫背景關系快取 Key,
    var dbContextKey = $"{typeof(TDbContext).FullName}_{connectionString}";

    // 從作業單元的快取當中獲取資料庫背景關系,不存在則呼叫 CreateDbContext() 創建,
    var databaseApi = unitOfWork.GetOrAddDatabaseApi(
        dbContextKey,
        () => new EfCoreDatabaseApi<TDbContext>(
            CreateDbContext(unitOfWork, connectionStringName, connectionString)
        ));

    return ((EfCoreDatabaseApi<TDbContext>)databaseApi).DbContext;
}

回到最開始的資料庫背景關系配置工廠,在它的內部會優先從一個 Current 獲取一個 DbContextCreationContext 實體,而在這里,就是 Current 被賦值的地方,只要呼叫了 Use() 方法,在釋放之前都會獲取到同一個實體,

private TDbContext CreateDbContext(IUnitOfWork unitOfWork, string connectionStringName, string connectionString)
{
    var creationContext = new DbContextCreationContext(connectionStringName, connectionString);
    using (DbContextCreationContext.Use(creationContext))
    {
        // 這里是重點,真正創建資料庫背景關系的地方,
        var dbContext = CreateDbContext(unitOfWork);

        if (unitOfWork.Options.Timeout.HasValue &&
            dbContext.Database.IsRelational() &&
            !dbContext.Database.GetCommandTimeout().HasValue)
        {
            dbContext.Database.SetCommandTimeout(unitOfWork.Options.Timeout.Value.TotalSeconds.To<int>());
        }

        return dbContext;
    }
}

// 如果是事務型的作業單元,則呼叫 CreateDbContextWithTransaction() 進行創建,但不論如何都是通過作業單元提供的 IServiceProvider 決議出來 DbContext 的,
private TDbContext CreateDbContext(IUnitOfWork unitOfWork)
{
    return unitOfWork.Options.IsTransactional
        ? CreateDbContextWithTransaction(unitOfWork)
        : unitOfWork.ServiceProvider.GetRequiredService<TDbContext>();
}

以下代碼才是在真正地創建 DbContext 實體,

public TDbContext CreateDbContextWithTransaction(IUnitOfWork unitOfWork) 
{
    var transactionApiKey = $"EntityFrameworkCore_{DbContextCreationContext.Current.ConnectionString}";
    var activeTransaction = unitOfWork.FindTransactionApi(transactionApiKey) as EfCoreTransactionApi;

    // 沒有取得快取,
    if (activeTransaction == null)
    {
        var dbContext = unitOfWork.ServiceProvider.GetRequiredService<TDbContext>();

        // 判斷是否指定了事務隔離級別,并開始事務,
        var dbtransaction = unitOfWork.Options.IsolationLevel.HasValue
            ? dbContext.Database.BeginTransaction(unitOfWork.Options.IsolationLevel.Value)
            : dbContext.Database.BeginTransaction();

        // 跟作業單元系結添加一個已經激活的事務,
        unitOfWork.AddTransactionApi(
            transactionApiKey,
            new EfCoreTransactionApi(
                dbtransaction,
                dbContext
            )
        );

        // 回傳構造好的資料庫背景關系,
        return dbContext;
    }
    else
    {
        DbContextCreationContext.Current.ExistingConnection = activeTransaction.DbContextTransaction.GetDbTransaction().Connection;

        var dbContext = unitOfWork.ServiceProvider.GetRequiredService<TDbContext>();

        if (dbContext.As<DbContext>().HasRelationalTransactionManager())
        {
            dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.GetDbTransaction());
        }
        else
        {
            dbContext.Database.BeginTransaction(); //TODO: Why not using the new created transaction?
        }

        activeTransaction.AttendedDbContexts.Add(dbContext);

        return dbContext;
    }
}

2.4 資料過濾器

ABP vNext 還提供了資料過濾器機制,可以讓你根據指定的標識過濾資料,例如租戶 Id 和軟洗掉標記,它的基本介面定義在 Volo.Abp.Data 專案的 IDataFilter.cs 檔案中,提供了啟用、禁用、檢測方法,

public interface IDataFilter<TFilter>
    where TFilter : class
{
    IDisposable Enable();

    IDisposable Disable();

    bool IsEnabled { get; }
}

public interface IDataFilter
{
    IDisposable Enable<TFilter>()
        where TFilter : class;
    
    IDisposable Disable<TFilter>()
        where TFilter : class;

    bool IsEnabled<TFilter>()
        where TFilter : class;
}

默認實作也在該專案下面的 DataFilter.cs 檔案,首先看以下 IDataFilter 的默認實作 DataFilter,內部有一個決議器和并發字典,這個并發字典存盤了所有的過濾器,其鍵是真實過濾器的型別(ISoftDeleteIMultiTenant),值是 DataFilter<TFilter>,具體物件根據 TFilter 的不同而不同,

public class DataFilter : IDataFilter, ISingletonDependency
{
    private readonly ConcurrentDictionary<Type, object> _filters;

    private readonly IServiceProvider _serviceProvider;

    public DataFilter(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _filters = new ConcurrentDictionary<Type, object>();
    }

    // ...
}

看一下其他的方法,都是對 IDataFilter<Filter> 的包裝,

public class DataFilter : IDataFilter, ISingletonDependency
{
    // ...

    public IDisposable Enable<TFilter>()
        where TFilter : class
    {
        return GetFilter<TFilter>().Enable();
    }

    public IDisposable Disable<TFilter>()
        where TFilter : class
    {
        return GetFilter<TFilter>().Disable();
    }

    public bool IsEnabled<TFilter>()
        where TFilter : class
    {
        return GetFilter<TFilter>().IsEnabled;
    }

    private IDataFilter<TFilter> GetFilter<TFilter>()
        where TFilter : class
    {
        // 并發字典當中獲取指定型別的過濾器,如果不存在則從 IoC 中決議,
        return _filters.GetOrAdd(
            typeof(TFilter),
            () => _serviceProvider.GetRequiredService<IDataFilter<TFilter>>()
        ) as IDataFilter<TFilter>;
    }
}

這么看來,IDataFilter 叫做 IDataFilterManager 更加合適一點,最開始我還沒搞明白兩個介面和實作的區別,真正搞事情的是 DataFilter<Filter>

public class DataFilter<TFilter> : IDataFilter<TFilter>
    where TFilter : class
{
    public bool IsEnabled
    {
        get
        {
            EnsureInitialized();
            return _filter.Value.IsEnabled;
        }
    }

    // 注入資料過濾器配置類,
    private readonly AbpDataFilterOptions _options;

    // 用于存盤過濾器的啟用狀態,
    private readonly AsyncLocal<DataFilterState> _filter;

    public DataFilter(IOptions<AbpDataFilterOptions> options)
    {
        _options = options.Value;
        _filter = new AsyncLocal<DataFilterState>();
    }

    // ...

    // 確保初始化成功,
    private void EnsureInitialized()
    {
        if (_filter.Value != null)
        {
            return;
        }

        // 如果過濾器的默認狀態為 NULL,優先從配置類中取得指定過濾器的默認啟用狀態,如果不存在則默認為啟用,
        _filter.Value = https://www.cnblogs.com/myzony/p/_options.DefaultStates.GetOrDefault(typeof(TFilter))?.Clone() ?? new DataFilterState(true);
    }
}

資料過濾器在設計的時候,也是按照作業單元的形式進行設計的,不論是啟用還是停用都是范圍性的,會回傳一個用 DisposeAction 包裝的可釋放物件,這樣在離開 using 陳述句塊的時候,就會還原為來的狀態,比如呼叫 Enable() 方法,在離開 using 陳述句塊之后,會呼叫 Disable() 禁用掉資料過濾器,

public IDisposable Enable()
{
    if (IsEnabled)
    {
        return NullDisposable.Instance;
    }

    _filter.Value.IsEnabled = true;

    return new DisposeAction(() => Disable());
}

public IDisposable Disable()
{
    if (!IsEnabled)
    {
        return NullDisposable.Instance;
    }

    _filter.Value.IsEnabled = false;

    return new DisposeAction(() => Enable());
}

2.4.1 MongoDb 與 Memory 的集成

可以看到有兩處使用,分別是 Volo.Abp.Domain 專案與 Volo.Abp.EntityFrameworkCore 專案,

首先看第一個專案的用法:

public abstract class RepositoryBase<TEntity> : BasicRepositoryBase<TEntity>, IRepository<TEntity>
    where TEntity : class, IEntity
{
    public IDataFilter DataFilter { get; set; }

    // ...

    // 分別在查詢的時候判斷物體是否實作了兩個介面,
    protected virtual TQueryable ApplyDataFilters<TQueryable>(TQueryable query)
        where TQueryable : IQueryable<TEntity>
    {
        // 如果實作了軟洗掉介面,則從 DataFilter 中獲取過濾器的開啟狀態,
        // 如果已經開啟,則過濾掉被洗掉的資料,
        if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
        {
            query = (TQueryable)query.WhereIf(DataFilter.IsEnabled<ISoftDelete>(), e => ((ISoftDelete)e).IsDeleted == false);
        }

        // 如果實作了多租戶介面,則從 DataFilter 中獲取過濾器的開啟狀態,
        // 如果已經開啟,則按照租戶 Id 過濾資料,
        if (typeof(IMultiTenant).IsAssignableFrom(typeof(TEntity)))
        {
            var tenantId = CurrentTenant.Id;
            query = (TQueryable)query.WhereIf(DataFilter.IsEnabled<IMultiTenant>(), e => ((IMultiTenant)e).TenantId == tenantId);
        }

        return query;
    }

    // ...
}

邏輯比較簡單,都是判斷物體是否實作某個介面,并且結合啟用狀態來進行過濾,在原有 IQuerable 拼接 WhereIf() 即可,但是 EF Core 使用這種方式不行,所以上述方法只會在 Memory 和 MongoDb 有使用,

2.4.2 EF Core 的集成

EF Core 集成資料過濾器則是放在資料庫背景關系基類 AbpDbContext<TDbContext> 中,在資料庫背景關系的 OnModelCreating() 方法內通過 ConfigureBasePropertiesMethodInfo 進行反射呼叫,

public abstract class AbpDbContext<TDbContext> : DbContext, IEfCoreDbContext, ITransientDependency
    where TDbContext : DbContext
{
    // ...
    protected virtual bool IsMultiTenantFilterEnabled => DataFilter?.IsEnabled<IMultiTenant>() ?? false;

    protected virtual bool IsSoftDeleteFilterEnabled => DataFilter?.IsEnabled<ISoftDelete>() ?? false;

    // ...

    public IDataFilter DataFilter { get; set; }

    // ...

    private static readonly MethodInfo ConfigureBasePropertiesMethodInfo = typeof(AbpDbContext<TDbContext>)
        .GetMethod(
            nameof(ConfigureBaseProperties),
            BindingFlags.Instance | BindingFlags.NonPublic
        );

    // ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            ConfigureBasePropertiesMethodInfo
                .MakeGenericMethod(entityType.ClrType)
                .Invoke(this, new object[] { modelBuilder, entityType });

            // ...
        }
    }

    // ...

    protected virtual void ConfigureBaseProperties<TEntity>(ModelBuilder modelBuilder, IMutableEntityType mutableEntityType)
        where TEntity : class
    {
        if (mutableEntityType.IsOwned())
        {
            return;
        }

        ConfigureConcurrencyStampProperty<TEntity>(modelBuilder, mutableEntityType);
        ConfigureExtraProperties<TEntity>(modelBuilder, mutableEntityType);
        ConfigureAuditProperties<TEntity>(modelBuilder, mutableEntityType);
        ConfigureTenantIdProperty<TEntity>(modelBuilder, mutableEntityType);
        // 在這里,配置全域過濾器,
        ConfigureGlobalFilters<TEntity>(modelBuilder, mutableEntityType);
    }

    // ...

    protected virtual void ConfigureGlobalFilters<TEntity>(ModelBuilder modelBuilder, IMutableEntityType mutableEntityType)
        where TEntity : class
    {
        // 符合條件則為其創建過濾運算式,
        if (mutableEntityType.BaseType == null && ShouldFilterEntity<TEntity>(mutableEntityType))
        {
            // 創建過濾運算式,
            var filterExpression = CreateFilterExpression<TEntity>();
            if (filterExpression != null)
            {
                // 為指定的物體配置查詢過濾器,
                modelBuilder.Entity<TEntity>().HasQueryFilter(filterExpression);
            }
        }
    }

    // ...

    // 判斷物體是否擁有過濾器,
    protected virtual bool ShouldFilterEntity<TEntity>(IMutableEntityType entityType) where TEntity : class
    {
        if (typeof(IMultiTenant).IsAssignableFrom(typeof(TEntity)))
        {
            return true;
        }

        if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
        {
            return true;
        }

        return false;
    }

    // 構建表達式,
    protected virtual Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
        where TEntity : class
    {
        Expression<Func<TEntity, bool>> expression = null;

        if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
        {
            expression = e => !IsSoftDeleteFilterEnabled || !EF.Property<bool>(e, "IsDeleted");
        }

        if (typeof(IMultiTenant).IsAssignableFrom(typeof(TEntity)))
        {
            Expression<Func<TEntity, bool>> multiTenantFilter = e => !IsMultiTenantFilterEnabled || EF.Property<Guid>(e, "TenantId") == CurrentTenantId;
            expression = expression == null ? multiTenantFilter : CombineExpressions(expression, multiTenantFilter);
        }

        return expression;
    }
        
    // ...
}

2.5 領域事件集成

在講解事件總線與 DDD 這塊的時候,我有提到過 ABP vNext 有實作領域事件功能,用戶可以在聚合根內部使用 AddLocalEvent(object eventData)AddDistributedEvent(object eventData) 添加了領域事件,

public abstract class AggregateRoot : Entity, 
    IAggregateRoot,
    IGeneratesDomainEvents, 
    IHasExtraProperties,
    IHasConcurrencyStamp
{
    // ...

    private readonly ICollection<object> _localEvents = new Collection<object>();
    private readonly ICollection<object> _distributedEvents = new Collection<object>();

    // ...

    // 添加本地事件,
    protected virtual void AddLocalEvent(object eventData)
    {
        _localEvents.Add(eventData);
    }

    // 添加分布式事件,
    protected virtual void AddDistributedEvent(object eventData)
    {
        _distributedEvents.Add(eventData);
    }

    // 獲得所有本地事件,
    public virtual IEnumerable<object> GetLocalEvents()
    {
        return _localEvents;
    }

    // 獲得所有分布式事件,
    public virtual IEnumerable<object> GetDistributedEvents()
    {
        return _distributedEvents;
    }

    // 清空聚合需要觸發的所有本地事件,
    public virtual void ClearLocalEvents()
    {
        _localEvents.Clear();
    }

    // 清空聚合需要觸發的所有分布式事件,
    public virtual void ClearDistributedEvents()
    {
        _distributedEvents.Clear();
    }
}

可以看到,我們在聚合內部執行任何業務行為的時候,可以通過上述的方法發送領域事件,那這些事件是在什么時候被發布的呢?

發現這幾個 Get 方法有被 AbpDbContext 所呼叫,其實在它的內部,會在每次 SaveChangesAsync() 的時候,遍歷所有物體,并獲取它們的本地事件與分布式事件集合,最后由 EntityChangeEventHelper 進行觸發,

public abstract class AbpDbContext<TDbContext> : DbContext, IEfCoreDbContext, ITransientDependency
    where TDbContext : DbContext
{
    // ...
    public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    {
        try
        {
            var auditLog = AuditingManager?.Current?.Log;

            List<EntityChangeInfo> entityChangeList = null;
            if (auditLog != null)
            {
                entityChangeList = EntityHistoryHelper.CreateChangeList(ChangeTracker.Entries().ToList());
            }

            var changeReport = ApplyAbpConcepts();

            var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);

            // 觸發領域事件,
            await EntityChangeEventHelper.TriggerEventsAsync(changeReport).ConfigureAwait(false);

            if (auditLog != null)
            {
                EntityHistoryHelper.UpdateChangeList(entityChangeList);
                auditLog.EntityChanges.AddRange(entityChangeList);
                Logger.LogDebug($"Added {entityChangeList.Count} entity changes to the current audit log");
            }

            return result;
        }
        catch (DbUpdateConcurrencyException ex)
        {
            throw new AbpDbConcurrencyException(ex.Message, ex);
        }
        finally
        {
            ChangeTracker.AutoDetectChangesEnabled = true;
        }
    }

    // ...

    protected virtual EntityChangeReport ApplyAbpConcepts()
    {
        var changeReport = new EntityChangeReport();

        // 遍歷所有的物體變更事件,
        foreach (var entry in ChangeTracker.Entries().ToList())
        {
            ApplyAbpConcepts(entry, changeReport);
        }

        return changeReport;
    }

    protected virtual void ApplyAbpConcepts(EntityEntry entry, EntityChangeReport changeReport)
    {
        // 根據不同的物體操作狀態,執行不同的操作,
        switch (entry.State)
        {
            case EntityState.Added:
                ApplyAbpConceptsForAddedEntity(entry, changeReport);
                break;
            case EntityState.Modified:
                ApplyAbpConceptsForModifiedEntity(entry, changeReport);
                break;
            case EntityState.Deleted:
                ApplyAbpConceptsForDeletedEntity(entry, changeReport);
                break;
        }

        // 添加領域事件,
        AddDomainEvents(changeReport, entry.Entity);
    }

    // ...

    protected virtual void AddDomainEvents(EntityChangeReport changeReport, object entityAsObj)
    {
        var generatesDomainEventsEntity = entityAsObj as IGeneratesDomainEvents;
        if (generatesDomainEventsEntity == null)
        {
            return;
        }

        // 獲取到所有的本地事件和分布式事件,將其加入到 EntityChangeReport 物件當中,
        var localEvents = generatesDomainEventsEntity.GetLocalEvents()?.ToArray();
        if (localEvents != null && localEvents.Any())
        {
            changeReport.DomainEvents.AddRange(localEvents.Select(eventData =https://www.cnblogs.com/myzony/p/> new DomainEventEntry(entityAsObj, eventData)));
            generatesDomainEventsEntity.ClearLocalEvents();
        }

        var distributedEvents = generatesDomainEventsEntity.GetDistributedEvents()?.ToArray();
        if (distributedEvents != null && distributedEvents.Any())
        {
            changeReport.DistributedEvents.AddRange(distributedEvents.Select(eventData => new DomainEventEntry(entityAsObj, eventData)));
            generatesDomainEventsEntity.ClearDistributedEvents();
        }
    }
}

轉到 `` 的內部,發現有如下代碼:

// ...
public async Task TriggerEventsAsync(EntityChangeReport changeReport)
{
    // 觸發領域事件,
    await TriggerEventsInternalAsync(changeReport).ConfigureAwait(false);

    if (changeReport.IsEmpty() || UnitOfWorkManager.Current == null)
    {
        return;
    }

    await UnitOfWorkManager.Current.SaveChangesAsync().ConfigureAwait(false);
}

protected virtual async Task TriggerEventsInternalAsync(EntityChangeReport changeReport)
{
    // 觸發默認的物體變更事件,例如某個物體被創建、修改、洗掉,
    await TriggerEntityChangeEvents(changeReport.ChangedEntities).ConfigureAwait(false);

    // 觸發用戶自己發送的領域事件,
    await TriggerLocalEvents(changeReport.DomainEvents).ConfigureAwait(false);
    await TriggerDistributedEvents(changeReport.DistributedEvents).ConfigureAwait(false);
}

// ...

protected virtual async Task TriggerLocalEvents(List<DomainEventEntry> localEvents)
{
    foreach (var localEvent in localEvents)
    {
        await LocalEventBus.PublishAsync(localEvent.EventData.GetType(), localEvent.EventData).ConfigureAwait(false);
    }
}

protected virtual async Task TriggerDistributedEvents(List<DomainEventEntry> distributedEvents)
{
    foreach (var distributedEvent in distributedEvents)
    {
        await DistributedEventBus.PublishAsync(distributedEvent.EventData.GetType(), distributedEvent.EventData).ConfigureAwait(false);
    }
}

三、系列文章目錄

點擊我 跳轉到文章總目錄,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/73226.html

標籤:.NET Core

上一篇:c#中為listbox的串列項添加右鍵選單

下一篇:pak 破解工具 如何使用

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more