正如您所说,您正在开发类库以使用库客户端传递的任何DbContext,那么您必须执行以下操作:
首先考虑你的类库有以下接口和类,你的DbContext 将被使用:
public interface IUnitOfWork
{
IRepository<T> Repository<T>() where T : class;
Task SaveChangesAsync();
}
internal class UnitOfWork : IUnitOfWork
{
private readonly DbContext _dbContext;
private Hashtable _repositories;
public UnitOfWork(DbContext dbContext)
{
_dbContext = dbContext;
}
public IRepository<T> Repository<T>() where T : class
{
if (_repositories == null)
_repositories = new Hashtable();
var type = typeof(T).Name;
if (!_repositories.ContainsKey(type))
{
var repositoryType = typeof(Repository<>);
var repositoryInstance =
Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), _dbContext);
_repositories.Add(type, repositoryInstance);
}
return (IRepository<T>)_repositories[type];
}
public async Task SaveChangesAsync()
{
await _dbContext.SaveChangesAsync();
}
}
public interface IRepository<TEntity> where TEntity : class
{
Task InsertEntityAsync(TEntity entity);
}
internal class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _dbContext;
public Repository(DbContext dbContext)
{
_dbContext = dbContext;
}
public async Task InsertEntityAsync(TEntity entity)
{
await _dbContext.Set<TEntity>().AddAsync(entity);
}
}
现在在你的类库中编写一个服务集合扩展方法如下:
public static class ServiceCollectionExtensions
{
public static void RegisterYourLibrary(this IServiceCollection services, DbContext dbContext)
{
if (dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
services.AddScoped<IUnitOfWork, UnitOfWork>(uow => new UnitOfWork(dbContext));
}
}
现在在您的客户端应用程序的Startup.ConfigureServices 中如下:
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("ConnectionStringName");
services.AddDbContext<AppDbContext>(option => option.UseSqlServer(connectionString));
ServiceProvider serviceProvider = services.BuildServiceProvider();
AppDbContext appDbContext = serviceProvider.GetService<AppDbContext>();
services.RegisterYourLibrary(appDbContext); // <-- Here passing the DbConext instance to the class library
.......
}
用法:
public class EmployeeController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public EmployeeController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<IActionResult> Insert()
{
Employee employee = new Employee();
await _unitOfWork.Repository<Employee>().InsertEntityAsync(employee);
await _unitOfWork.SaveChangesAsync();
return View();
}
}