多层架构在业务逻辑层实现IOC
在业务逻辑层实现IOC,可以有效的减少代码量,把通用的操作写在通用的类中,然后在UI层对谁操作就建立谁的实例。
具体做法看代码:
Service层核心代码:
接口规范:
namespace Service
{
/// <summary>
/// 标准逻辑处理接口
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public interface IServices<TEntity> where TEntity : class,Entity.IDataEntity
{
/// <summary>
/// 获得List结果集
/// </summary>
/// <returns></returns>
List<IDataEntity> GetModelList();
/// <summary>
/// 获得IQueryable结果集
/// </summary>
/// <returns></returns>
IQueryable<IDataEntity> GetModelIQueryable();
/// <summary>
/// 根据主键得到一个实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
TEntity GetModelById(string id);
/// <summary>
/// 插入实体
/// </summary>
/// <param name="entity"></param>
void InsertModel(TEntity entity);
/// <summary>
/// 更新实体
/// </summary>
/// <param name="entity"></param>
void UpdateModel(TEntity entity);
/// <summary>
/// 删除单个实体
/// </summary>
/// <param name="key"></param>
void DeleteModel(params object[] key);
}
}
实现:
namespace Service
{
/// <summary>
/// 标准逻辑实现CURD
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class Services<TEntity> : IServices<TEntity>
where TEntity : class,Entity.IDataEntity
{
IRepository iRepository = null;
/// <summary>
/// 构造函数实现IOC
/// </summary>
/// <param name="iRepository"></param>
public Services(IRepository iRepository)
{
this.iRepository = iRepository;
}
public Services()
{
}
#region IServices<TEntity> 成员
public List<IDataEntity> GetModelList()
{
return this.iRepository.GetModel().ToList();
}
public IQueryable<IDataEntity> GetModelIQueryable()
{
return this.iRepository.GetModel();
}
public TEntity GetModelById(string id)
{
throw new NotImplementedException();
}
public void InsertModel(TEntity entity)
{
this.iRepository.Insert(entity);
}
public void UpdateModel(TEntity entity)
{
this.iRepository.Insert(entity);
}
public void DeleteModel(params object[] key)
{
this.iRepository.Delete(key);
}
#endregion
}
}
具体业务对象:为了使UI层不直接调用Data层的尴尬
namespace Service
{
public class UserServices
{
public Data.IRepository UserBasesRepository
{
get
{
return new Data.OA.UserBasesRepository();
}
}
}
}
UI层调用Service层代码:
IServices<Entity.OA.UserBase> iServices = null;
public ActionResult Index()
{
ViewBag.Message = "欢迎使用 ASP.NET MVC!";
iServices = new Services<Entity.OA.UserBase>(new UserServices().UserBasesRepository);
ViewData["UserBase"] = iServices.GetModelList().Cast<Entity.OA.UserBase>().ToList();
return View();
}