Skip to content

Instantly share code, notes, and snippets.

@hyrmn
Created Dec 2, 2019
Embed
What would you like to do?
public class PartitionedNamingStrategy
{
private static readonly Dictionary<string, Func<string, string>> NamingStrategies = new Dictionary<string, Func<string, string>>
{
{"none", s => s},
{"bymachine", s => $"{Environment.MachineName}_{s}"}
};
private readonly string _strategy;
public PartitionedNamingStrategy(string strategy = "none")
{
_strategy = strategy.ToLower();
}
public string GetPartitionedName(string namedThing)
{
return NamingStrategies[_strategy](namedThing);
}
}
public class ServiceBus
{
public SubscriptionClient CreateSubscriptionClient(string topic, string subscriptionName,
ReceiveMode receiveMode = ReceiveMode.PeekLock)
{
var topicDescription = GetOrCreateTopic(topic);
if (!_primaryNamespace.Value.SubscriptionExists(topicDescription.Path, subscriptionName))
{
_primaryNamespace.Value.CreateSubscription(topicDescription.Path, subscriptionName);
}
return _messagingFactory.Value.CreateSubscriptionClient(topicDescription.Path, subscriptionName, receiveMode);
}
public TopicClient CreateTopicClient(string topic)
{
return _messagingFactory.Value.CreateTopicClient(GetOrCreateTopic(topic).Path);
}
private TopicDescription GetOrCreateTopic(string topic)
{
var partitionedName = _partitionedNamingStrategy.GetPartitionedName(topic);
if (_primaryNamespace.Value.TopicExists(partitionedName))
{
var topicDescription = _primaryNamespace.Value.GetTopic(partitionedName);
return topicDescription;
}
var newTopic = new TopicDescription(partitionedName) {EnablePartitioning = true};
return _primaryNamespace.Value.CreateTopic(newTopic);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment