I would advise registering the IConnection
as a singleton.
To register the IConnection
as a singleton in Unity you would use a ContainerControlledLifetimeManager
, e.g.
var connectionFactory = new ConnectionFactory
{
// Configure the connection factory
};
unityContainer.RegisterInstance(connectionFactory);
unityContainer.RegisterType<IConnection, AutorecoveringConnection>(new ContainerControlledLifetimeManager(),
new InjectionMethod("init"));
The AutorecoveringConnection
instance, once resolved for the first time will stay alive until the owning UnityContainer
is disposed.
Because we have registered the ConnectionFactory
with Unity
, this will automatically be injected into the constructor of AutorecoveringConnection
.
The InjectionMethod
ensures that the first time the AutorecoveringConnection
is resolved, the init
method is invoked.
As for your question about whether you should abstract away RabbitMQ from your services, my answer would be yes, however I would not simply create an IMessageQueue
abstraction. Think about what purpose you are using your message queue for, is it to push statuses? If so, have an IStatusNotifier
interface with a concrete implementation for RabbitMQ. If it's to fetch updates, have an IUpdateSource
interface with a concrete implementation for RabbitMQ. You can see where I am going with this.
If you create an abstraction for a Message Queue, you are limiting yourself to features only available across all Message Queue implementations. By having a different implementation of IStatusNotifier
for different Message Queue implementations, you are able to take advantage of features which are unique to different technologies while also remaining flexible in case completely different technologies are employed in future (e.g. Writing to a SQL database or outputting to a console).