C# 通用存储库的静态成员/类
我有一个dapper泛型存储库类,因为.NETCore不支持分布式事务,所以我决定将已经打开的连接对象发送到泛型方法,而不是在存储库中单独注入C# 通用存储库的静态成员/类,c#,asp.net-core,dapper,C#,Asp.net Core,Dapper,我有一个dapper泛型存储库类,因为.NETCore不支持分布式事务,所以我决定将已经打开的连接对象发送到泛型方法,而不是在存储库中单独注入 public class Repository<T> where T: class { protected readonly IComplianceConnection Connection; public Repository(IComplianceConnection connection) {
public class Repository<T> where T: class
{
protected readonly IComplianceConnection Connection;
public Repository(IComplianceConnection connection)
{
Connection = connection;
}
public IEnumerable<T> Get(string query, object arguments)
{
IList<T> entities;
using (var connection = Connection.OpenConnection())
{
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
}
return entities;
}
}
public static class Repository<T> where T: class
{
public static IEnumerable<T> Get(this IDbConnection connection, string query, object arguments)
{
IList<T> entities;
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
return entities;
}
}
我需要将这个类更改为静态类。下面是新的存储库
public class Repository<T> where T: class
{
protected readonly IComplianceConnection Connection;
public Repository(IComplianceConnection connection)
{
Connection = connection;
}
public IEnumerable<T> Get(string query, object arguments)
{
IList<T> entities;
using (var connection = Connection.OpenConnection())
{
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
}
return entities;
}
}
public static class Repository<T> where T: class
{
public static IEnumerable<T> Get(this IDbConnection connection, string query, object arguments)
{
IList<T> entities;
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
return entities;
}
}
通用存储库的这种静态方法正确吗。。请建议我我的理解是扩展方法作用于类的实例。在Get方法中,该实例是连接参数。但是,您似乎正在覆盖Get方法中的连接实例。这可能不是所希望的 您可能不想创建扩展方法。也许您只需要一个可以接受IComplianceConnection参数的静态方法
public static IEnumerable<T> Get(IComplianceConnection complianceConnection, string query, object arguments)
{
IList<T> entities;
using (var connection = complianceConnection.OpenConnection())
{
entities = connection.Query<T>(query, arguments, commandType: CommandType.StoredProcedure).ToList();
}
return entities;
}
希望这有帮助 一,。我不认为使用是合适的,也许连接已经建立了??。2.为什么不把这个方法放在DbContext上?你能提供一个示例代码吗