Skip to content

Create a service discovery client with Autofac

dilandau2001 edited this page Feb 3, 2023 · 1 revision

As stated in the readme, this library has injection in mind.
So this is a small guide about how you would add a client to your application using autofac and how to consume it.

My recomendation is to use your own version of a “DeviceClient” that would make use of the client from the library. This recommendation will allow you to make an interface of the client and will make your application “independant” on direct references to the external library.

Although, as I said, is not the recomended approach, the easiest module you could create is like the following:


using Autofac;
using Dilan.GrpcServiceDiscovery.Grpc;

    public class DiscoveryModule : Module
    {
        /// <summary>
        /// Register services into the container builder
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ClientConfigurationOptions>();
            builder.RegisterType<MulticastClient>().As<IMulticastClient>().AsSelf();
            builder.RegisterType<SystemInfoMetadataProvider>().As<IMetadataProvider>().AsSelf();
            builder.RegisterType<ServiceDiscoveryClient>().SingleInstance();
        }
    }

You can inject more implementations of IMetadataProvider, build on your own. Those will be loaded by the client in order to publish new metatadata topics to the registrar server. Providers are called on a time basis configured in the server side so dont make too heavy logic for metadata providers. The default one will send process name, cpu and private memory used.

You will probably want to modify default values of ClientConfigurationOptions before injecting it. In that case you will register it as an instance like:


// Create options.
ClientConfigurationOptions myOptions = new ClientConfigurationOptions();

// Set option values as desired

// Register the instance
builder.RegisterInstance(myOptions).SingleInstance();

You can also modify options after it is created and before calling start. You would do all this logic in your own implementation of the client.

Clone this wiki locally