Skip to content

Instantly share code, notes, and snippets.

@hyrmn
Created December 2, 2019 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyrmn/2d9673837f547dbe3c3121346dd6ac99 to your computer and use it in GitHub Desktop.
Save hyrmn/2d9673837f547dbe3c3121346dd6ac99 to your computer and use it in GitHub Desktop.
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