如何在数据访问层接口中使用通用方法?

时间:2017-10-29 04:55:21

标签: c#

我希望有一个泛型方法,将一些已知类型转换为数据库接受的等效类型,以插入它们。

public class MongoDataAccess : IDataAccess
{
    public Task InsertAsync<T>(string collectionName, T item)
    {
        // convert T which should be `Student`, `University` etc
        // to `StudentDocument`, 'UniversityDocument` etc
    }
}

如何使用接口来应用限制?

2 个答案:

答案 0 :(得分:1)

除了拥有&#34;数据访问外观&#34; IDataAccess,您可以实现&#34;实体处理程序&#34;每个实体类型{学生,大学等)IDataAccess<T>。应用程序代码将#34; talk&#34;到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 Facade将调用委托给具体实体处理程序的方式:

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
        };
}

答案 1 :(得分:0)

使用此界面。

IConvertible<TSource, TResult>
{
    Task<TResult> Convert(string collectionName);
}

您的数据类型(如学生和大学)必须通过此实现。