📅  最后修改于: 2022-03-11 14:49:01.286000             🧑  作者: Mango
My current solve:
Create Cluster:
cluster = Cluster.Builder()
.AddContactPoint(cassandraData.ContactPoint)
.WithPort(int.Parse(cassandraData.Port))
.WithCredentials(cassandraData.User, cassandraData.Password)
.Build();
After that i inject this by dependency injection to my Session Cache:
public CassandraSessionCache(Cluster cluster)
{
_cluster = cluster;
_sessions = new ConcurrentDictionary>();
}
public ISession GetSession(string keyspaceName)
{
if (!_sessions.ContainsKey(keyspaceName))
_sessions.GetOrAdd(keyspaceName, key => new Lazy(() =>
_cluster.Connect(key)));
var result = _sessions[keyspaceName];
return result.Value;
}
I Create also Map to Cassandra and use it my startup class.
After this configuration my repository look like this:
public class TestRepository : ITestRepository
{
private readonly CassandraSessionCache _cassandra;
private Mapper _mapper;
public TestRepository(CassandraSessionCache cassandra)
{
_cassandra = cassandra;
}
public async Task DeleteAsync(Guid id, string keySpace)
{
SetSessionAndMapper(keySpace);
await _mapper.DeleteAsync("WHERE id = ?", id);
}
public async Task GetAsync(string id, string keySpace)
{
SetSessionAndMapper(keySpace);
return await _mapper.FirstOrDefaultAsync("SELECT * FROM \"Test\" WHERE id = ?", id);
}
public async Task PostAsync(Test data, string keySpace)
{
SetSessionAndMapper(keySpace);
await _mapper.InsertAsync(data);
}
private void SetSessionAndMapper(string keySpace)
{
var session = _cassandra.GetSession(keySpace);
_mapper = new Mapper(session);
}
}