[英]How to have a generic method in a data access layer interface?
我想要一個通用方法,該方法將一些已知類型轉換為數據庫可接受的等效類型以插入它們。
public class MongoDataAccess : IDataAccess
{
public Task InsertAsync<T>(string collectionName, T item)
{
// convert T which should be `Student`, `University` etc
// to `StudentDocument`, 'UniversityDocument` etc
}
}
如何執行此操作,可能使用接口來施加限制?
除了具有“數據訪問外觀” IDataAccess
,您還可以IDataAccess<T>
每種實體類型(學生,大學等)實現“實體處理程序” IDataAccess<T>
。 應用程序代碼將與DAL外觀進行“對話”,DAL外觀將委托給具體的實體處理程序。
DAL外觀可以如下所示:
public interface IDataAccess<TEntity>
{
// no need for collectionName parameter
// because each concrete entity handler knows its collection name
Task InsertAsync(TEntity entity);
// .... other CRUD methods
}
具體的實體處理程序的實現如下所示:
public class StudentDataAccess : IDataAccess<Student>
{
// initialized elsewhere in this class
private MongoCollection<StudentDocument> _collection;
public Task InsertAsync(Student entity)
{
var document = ConvertToDocument(entity);
return _collection.InsertOneAsync(document);
}
private StudentDocument ConvertToDocument(Student entity)
{
// perform the conversion here....
}
}
這是DAL外觀將調用委派給具體實體處理程序的方式:
public class DataAccess
{
public async Task InsertAsync<T>(T entity)
{
//... obtain an instance of IDataAccess<T>
var enityHandler = GetEntityHandler<T>();
return entityHandler.InsertAsync(entity);
}
private IDataAccess<T> GetEntityHandler<T>()
{
// you can use a DI container library like Autofac
// or just implement your own simpliest service locator like this:
return (IDataAccess<T>)_handlerByEntityType[typeof(T)];
}
// the following simplest service locator can be replaced with a
// full-blown DI container like Autofac
private readonly IReadOnlyDictionary<Type, object> _handlerByEntityType =
new Dictionary<Type, object> {
{ typeof(Student), new StudentDataAccess() },
{ typeof(University), new UniversityDataAccess() },
// ... the rest of your entities
};
}
使用此界面。
IConvertible<TSource, TResult>
{
Task<TResult> Convert(string collectionName);
}
您的學生和大學等數據類型必須從此實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.