Skip to content

Commit

Permalink
修改IOptionsMonitor;修改MS DI的AddSurpass和UseSurpass方法
Browse files Browse the repository at this point in the history
  • Loading branch information
lukangkang committed Sep 22, 2017
1 parent e2db144 commit c36ea80
Show file tree
Hide file tree
Showing 32 changed files with 234 additions and 164 deletions.
17 changes: 9 additions & 8 deletions Surpass-Server/Surpass.Domain/Repositories/RepositoryBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Surpass.Database;
using Surpass.Domain.Repositories.Interfaces;
Expand All @@ -16,13 +17,13 @@ public abstract class RepositoryBase<TEntity, TPrimaryKey> : IRepositoryBase<TEn
/// <summary>
/// 获取工作单元
/// </summary>
protected virtual IUnitOfWork UnitOfWork => Application.Ioc.GetService<IUnitOfWork>();
protected IUnitOfWork UnitOfWork => Application.Provider.GetService<IUnitOfWork>();

/// <summary>
/// 查询实体
/// 受这些过滤器的影响: 查询过滤器
/// </summary>
public virtual IQueryable<TEntity> Query()
public IQueryable<TEntity> Query()
{
var uow = UnitOfWork;
var query = uow.Context.Query<TEntity>();
Expand All @@ -33,7 +34,7 @@ public virtual IQueryable<TEntity> Query()
/// 获取符合条件的单个实体
/// 受这些过滤器的影响: 查询过滤器
/// </summary>
public virtual TEntity Get(Expression<Func<TEntity, bool>> predicate)
public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return Query().FirstOrDefault(predicate);
}
Expand All @@ -51,7 +52,7 @@ public long Size(Expression<Func<TEntity, bool>> predicate)
/// 添加或更新实体
/// 受这些过滤器的影响: 操作过滤器
/// </summary>
public virtual void Save(ref TEntity entity, Action<TEntity> update = null)
public void Save(ref TEntity entity, Action<TEntity> update = null)
{
var uow = UnitOfWork;
update = uow.WrapUpdateMethod<TEntity, TPrimaryKey>(update);
Expand All @@ -62,7 +63,7 @@ public virtual void Save(ref TEntity entity, Action<TEntity> update = null)
/// 删除实体
/// 受这些过滤器的影响: 操作过滤器
/// </summary>
public virtual void Delete(TEntity entity)
public void Delete(TEntity entity)
{
var uow = UnitOfWork;
uow.WrapBeforeDeleteMethod<TEntity, TPrimaryKey>(e => { })(entity);
Expand All @@ -73,7 +74,7 @@ public virtual void Delete(TEntity entity)
/// 批量保存实体
/// 受这些过滤器的影响: 操作过滤器
/// </summary>
public virtual void BatchSave(
public void BatchSave(
ref IEnumerable<TEntity> entities, Action<TEntity> update = null)
{
var uow = UnitOfWork;
Expand All @@ -85,7 +86,7 @@ public virtual void BatchSave(
/// 批量更新实体
/// 受这些过滤器的影响: 查询过滤器, 操作过滤器
/// </summary>
public virtual long BatchUpdate(
public long BatchUpdate(
Expression<Func<TEntity, bool>> predicate, Action<TEntity> update)
{
var uow = UnitOfWork;
Expand All @@ -98,7 +99,7 @@ public virtual long BatchUpdate(
/// 批量删除实体
/// 受这些过滤器的影响: 查询过滤器, 操作过滤器
/// </summary>
public virtual long BatchDelete(
public long BatchDelete(
Expression<Func<TEntity, bool>> predicate, Action<TEntity> beforeDelete)
{
var uow = UnitOfWork;
Expand Down
28 changes: 12 additions & 16 deletions Surpass-Server/Surpass.Domain/Services/Bases/DomainServiceBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ public abstract class DomainServiceBase : IDomainService {
/// <summary>
/// 获取工作单元
/// </summary>
protected virtual IUnitOfWork UnitOfWork {
get { return Application.Ioc.GetService<IUnitOfWork>(); }
}
protected IUnitOfWork UnitOfWork => Application.Provider.GetService<IUnitOfWork>();
}

/// <summary>
Expand All @@ -38,14 +36,12 @@ public abstract class DomainServiceBase<TEntity, TPrimaryKey> :
/// <summary>
/// 获取仓储
/// </summary>
protected virtual IRepositoryBase<TEntity, TPrimaryKey> Repository {
get { return Application.Ioc.GetService<IRepositoryBase<TEntity, TPrimaryKey>>(); }
}
protected IRepositoryBase<TEntity, TPrimaryKey> Repository => Application.Provider.GetService<IRepositoryBase<TEntity, TPrimaryKey>>();

/// <summary>
/// <summary>
/// 根据主键获取实体
/// </summary>
public virtual TEntity Get(TPrimaryKey id) {
public TEntity Get(TPrimaryKey id) {
if (id.Equals(default(TPrimaryKey))) {
return default(TEntity);
}
Expand All @@ -58,7 +54,7 @@ public virtual TEntity Get(TPrimaryKey id) {
/// <summary>
/// 根据条件获取实体
/// </summary>
public virtual TEntity Get(Expression<Func<TEntity, bool>> predicate) {
public TEntity Get(Expression<Func<TEntity, bool>> predicate) {
using (UnitOfWork.Scope()) {
return Repository.Get(predicate);
}
Expand All @@ -67,7 +63,7 @@ public virtual TEntity Get(Expression<Func<TEntity, bool>> predicate) {
/// <summary>
/// 根据条件获取实体列表
/// </summary>
public virtual IList<TEntity> GetMany(
public IList<TEntity> GetMany(
Expression<Func<TEntity, bool>> predicate = null) {
using (UnitOfWork.Scope()) {
var query = Repository.Query();
Expand All @@ -81,7 +77,7 @@ public virtual IList<TEntity> GetMany(
/// <summary>
/// 根据过滤函数获取实体列表
/// </summary>
public virtual TResult GetMany<TResult>(
public TResult GetMany<TResult>(
Func<IQueryable<TEntity>, TResult> fetch) {
using (UnitOfWork.Scope()) {
return fetch(Repository.Query());
Expand All @@ -100,7 +96,7 @@ public long Size(Expression<Func<TEntity, bool>> predicate) {
/// <summary>
/// 保存实体
/// </summary>
public virtual void Save(ref TEntity entity, Action<TEntity> update = null) {
public void Save(ref TEntity entity, Action<TEntity> update = null) {
using (UnitOfWork.Scope()) {
Repository.Save(ref entity, update);
}
Expand All @@ -109,7 +105,7 @@ public virtual void Save(ref TEntity entity, Action<TEntity> update = null) {
/// <summary>
/// 根据主键删除实体
/// </summary>
public virtual bool Delete(TPrimaryKey id) {
public bool Delete(TPrimaryKey id) {
var expr = ExpressionUtils.MakeMemberEqualiventExpression<TEntity>("Id", id);
using (UnitOfWork.Scope()) {
return Repository.BatchDelete(expr) > 0;
Expand All @@ -119,7 +115,7 @@ public virtual bool Delete(TPrimaryKey id) {
/// <summary>
/// 删除实体
/// </summary>
public virtual void Delete(TEntity entity) {
public void Delete(TEntity entity) {
using (UnitOfWork.Scope()) {
Repository.Delete(entity);
}
Expand All @@ -129,7 +125,7 @@ public virtual void Delete(TEntity entity) {
/// 批量标记已删除或未删除
/// 返回标记的数量,不会实际删除
/// </summary>
public virtual long BatchSetDeleted(IEnumerable<TPrimaryKey> ids, bool deleted) {
public long BatchSetDeleted(IEnumerable<TPrimaryKey> ids, bool deleted) {
var uow = UnitOfWork;
using (uow.Scope())
using (uow.DisableQueryFilter(typeof(DeletedFilter))) {
Expand All @@ -143,7 +139,7 @@ public virtual long BatchSetDeleted(IEnumerable<TPrimaryKey> ids, bool deleted)
/// <summary>
/// 批量永久删除
/// </summary>
public virtual long BatchDeleteForever(IEnumerable<TPrimaryKey> ids) {
public long BatchDeleteForever(IEnumerable<TPrimaryKey> ids) {
var uow = UnitOfWork;
using (uow.Scope())
using (uow.DisableQueryFilter(typeof(DeletedFilter))) {
Expand Down
6 changes: 3 additions & 3 deletions Surpass-Server/Surpass.Domain/Uow/UnitOfWork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ private class ScopeData : IDisposable
/// </summary>
public ScopeData()
{
var databaseManager = Application.Ioc.GetService<DatabaseManager>();
var databaseManager = Application.Provider.GetService<DatabaseManager>();
Context = databaseManager.CreateContext();
QueryFilters = Application.Ioc.GetServices<IEntityQueryFilter>().ToList();
OperationFilters = Application.Ioc.GetServices<IEntityOperationFilter>().ToList();
QueryFilters = Application.Provider.GetServices<IEntityQueryFilter>().ToList();
OperationFilters = Application.Provider.GetServices<IEntityOperationFilter>().ToList();
}

/// <summary>
Expand Down
8 changes: 4 additions & 4 deletions Surpass-Server/Surpass.ORM.EFCore/EFCoreDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ protected void InsertOrUpdate<T>(T entity, Action<T> update = null)
public void Save<T>(ref T entity, Action<T> update = null)
where T : class, IEntity
{
var callbacks = Application.Ioc.GetServices<IEntityOperationHandler<T>>().ToList();
var callbacks = Application.Provider.GetServices<IEntityOperationHandler<T>>().ToList();
var entityLocal = entity; // can't use ref parameter in lambda
callbacks.ForEach(c => c.BeforeSave(this, entityLocal)); // notify before save
InsertOrUpdate(entityLocal, update);
Expand All @@ -306,7 +306,7 @@ public void BatchSave<T>(ref IEnumerable<T> entities, Action<T> update = null)
where T : class, IEntity
{
var entitiesLocal = entities.ToList();
var callbacks = Application.Ioc.GetServices<IEntityOperationHandler<T>>().ToList();
var callbacks = Application.Provider.GetServices<IEntityOperationHandler<T>>().ToList();
foreach (var entity in entitiesLocal)
{
callbacks.ForEach(c => c.BeforeSave(this, entity)); // notify before save
Expand Down Expand Up @@ -404,7 +404,7 @@ public void FastBatchSave<T, TPrimaryKey>(IEnumerable<T> entities)
public void Delete<T>(T entity)
where T : class, IEntity
{
var callbacks = Application.Ioc.GetServices<IEntityOperationHandler<T>>().ToList();
var callbacks = Application.Provider.GetServices<IEntityOperationHandler<T>>().ToList();
callbacks.ForEach(c => c.BeforeDelete(this, entity)); // notify before delete
Remove(entity);
SaveChanges(); // send commands to database
Expand All @@ -420,7 +420,7 @@ public long BatchDelete<T>(Expression<Func<T, bool>> predicate, Action<T> before
where T : class, IEntity
{
var entities = Query<T>().Where(predicate).ToList();
var callbacks = Application.Ioc.GetServices<IEntityOperationHandler<T>>().ToList();
var callbacks = Application.Provider.GetServices<IEntityOperationHandler<T>>().ToList();
foreach (var entity in entities)
{
beforeDelete?.Invoke(entity);
Expand Down
12 changes: 6 additions & 6 deletions Surpass-Server/Surpass.ORM.EFCore/EFCoreDbContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class EFCoreDatabaseContextFactory : IDatabaseContextFactory
/// Namespace for model snapshot<br/>
/// 模型快照的命名空间<br/>
/// </summary>
protected const string ModelSnapshotNamespace = "ZKWeb.ORM.EFCore.Migrations";
protected const string ModelSnapshotNamespace = "Surpass.ORM.EFCore.Migrations";
/// <summary>
/// Class name prefix for model snapshot<br/>
/// 模型快照的类名前缀<br/>
Expand Down Expand Up @@ -69,8 +69,8 @@ public class EFCoreDatabaseContextFactory : IDatabaseContextFactory
/// </summary>
public EFCoreDatabaseContextFactory(string database, string connectionString) :
this(database, connectionString,
Application.Ioc.GetServices<IDatabaseInitializeHandler>(),
Application.Ioc.GetServices<IEntityMappingProvider>())
Application.Provider.GetServices<IDatabaseInitializeHandler>(),
Application.Provider.GetServices<IEntityMappingProvider>())
{ }

/// <summary>
Expand All @@ -90,7 +90,7 @@ public EFCoreDatabaseContextFactory(
new EFCoreDbContext(Database, ConnectionString, Handlers, Providers));
// Check if database auto migration is disabled
//判断是否要禁用数据库自动迁移
//var configManager = Application.Ioc.GetServices<WebsiteConfigManager>();
//var configManager = Application.Provider.GetServices<WebsiteConfigManager>();
//var noAutoMigration = configManager.WebsiteConfig.Extra.GetOrDefault<bool?>(
// EFCoreExtraConfigKeys.DisableEFCoreDatabaseAutoMigration) ?? false;
//if (!noAutoMigration)
Expand Down Expand Up @@ -158,8 +158,8 @@ protected void MigrateRelationalDatabase(DbContext context, IModel initialModel)
var assemblyName = ModelSnapshotFilePrefix + DateTime.UtcNow.Ticks;
var codePath = Path.Combine(tempPath, assemblyName + ".cs");
var assemblyPath = Path.Combine(tempPath, assemblyName + ".dll");
var compileService = Application.Ioc.GetService<ICompilerService>();
var assemblyLoader = Application.Ioc.GetService<IAssemblyLoader>();
var compileService = Application.Provider.GetService<ICompilerService>();
var assemblyLoader = Application.Provider.GetService<IAssemblyLoader>();
File.WriteAllText(codePath, lastMigration.Model);
compileService.Compile(new[] { codePath }, assemblyName, assemblyPath);
// Load assembly and create the snapshot instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public void Map<TMember>(
if (options.WithSerialization == true)
{
// log error only, some functions may not work
var logManager = Application.Ioc.GetService<ILoggerFactory>().CreateLogger<EFCoreEntityMappingBuilder<T>>();
var logManager = Application.Provider.GetService<ILoggerFactory>().CreateLogger<EFCoreEntityMappingBuilder<T>>();
logManager.LogError(
"Entity framework core not support custom type mapping yet, " +
"see https://github.com/aspnet/EntityFramework/issues/242 " +
Expand Down Expand Up @@ -245,7 +245,7 @@ public void HasManyToMany<TChild>(
where TChild : class
{
// log error only, some functions may not work
var logManager = Application.Ioc.GetService<ILoggerFactory>().CreateLogger<EFCoreEntityMappingBuilder<T>>();
var logManager = Application.Provider.GetService<ILoggerFactory>().CreateLogger<EFCoreEntityMappingBuilder<T>>();
logManager.LogError(
"Entity framework core not support many-to-many yet, " +
"see https://github.com/aspnet/EntityFramework/issues/1368 " +
Expand Down
9 changes: 6 additions & 3 deletions Surpass-Server/Surpass.Web/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Surpass.Domain.Entities;
using Surpass.Domain.Repositories.Interfaces;
using Surpass.ORM.EFCore;

namespace Surpass.Web.Controllers
Expand All @@ -12,16 +13,18 @@ public class UsersController : Controller
{
private readonly EFCoreDbContext _context;

public UsersController(EFCoreDbContext context)
{
private readonly IRepositoryBase<User, Guid> _userRepository;

public UsersController(EFCoreDbContext context, IRepositoryBase<User, Guid> userRepository)
{
_context = context;
_userRepository = userRepository;
}

// GET: Users
public async Task<IActionResult> Index()
{
return View(await _context.FindAsync<List<User>>());
return View(await _userRepository.Query().ToListAsync());
}

// GET: Users/Details/5
Expand Down
29 changes: 20 additions & 9 deletions Surpass-Server/Surpass.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Surpass.Database;
using Surpass.Plugin;
using SurpassStandard.Options;

namespace Surpass.Web
{
Expand Down Expand Up @@ -44,7 +43,7 @@ private static string GetWebsiteRootDirectory()
}

// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization();
services.AddLogging(builder =>
Expand All @@ -70,15 +69,14 @@ public IServiceProvider ConfigureServices(IServiceCollection services)
services.AddMvc();
services.AddLogging();

services.AddOptions();
services.Configure<DatabaseOptions>(Configuration.GetSection("Databases"));
services.Configure<PluginOptions>(Configuration.GetSection("Plugins"));
services.AddOptions().Configure<BaseInfoOptions>(Configuration.GetSection("BaseInfo"))
.Configure<DatabaseOptions>(Configuration.GetSection("Databases"))
.Configure<PluginOptions>(Configuration.GetSection("Plugins"));


services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Application.Initialize(services, GetWebsiteRootDirectory());

return services.BuildServiceProvider();
Application.AddSurpass(services);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand All @@ -97,12 +95,25 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseStaticFiles();
app.UseAuthentication();

//允许跨域访问
app.UseCors(builder =>
{
builder.AllowAnyHeader();
builder.AllowAnyMethod();
//生开发环境
builder.AllowAnyOrigin();
//生产环境
//builder.WithOrigins("http://localhost:80");
});

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

Application.UseSurpass(app, GetWebsiteRootDirectory());
}
}
}
1 change: 0 additions & 1 deletion Surpass-Server/Surpass.Web/Surpass.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
</ItemGroup>

<ItemGroup>
<Folder Include="Models\" />
<Folder Include="Properties\PublishProfiles\" />
<Folder Include="Views\Shared\" />
<Folder Include="wwwroot\css\" />
Expand Down
Loading

0 comments on commit c36ea80

Please sign in to comment.