Lifetimes of .NET Dapr pluggable components

How to control the lifetime of a .NET pluggable component

There are two ways to register a component:

  • The component operates as a singleton, with lifetime managed by the SDK
  • A component’s lifetime is determined by the pluggable component and can be multi-instance or a singleton, as needed

Singleton components

Components registered by type are singletons: one instance will serve all configured components of that type associated with that socket. This approach is best when only a single component of that type exists and is shared amongst Dapr applications.

  1. var app = DaprPluggableComponentsApplication.Create();
  2. app.RegisterService(
  3. "service-a",
  4. serviceBuilder =>
  5. {
  6. serviceBuilder.RegisterStateStore<SingletonStateStore>();
  7. });
  8. app.Run();
  9. class SingletonStateStore : IStateStore
  10. {
  11. // ...
  12. }

Multi-instance components

Components can be registered by passing a “factory method”. This method will be called for each configured component of that type associated with that socket. The method returns the instance to associate with that component (whether shared or not). This approach is best when multiple components of the same type may be configured with different sets of metadata, when component operations need to be isolated from one another, etc.

The factory method will be passed context, such as the ID of the configured Dapr component, that can be used to differentiate component instances.

  1. var app = DaprPluggableComponentsApplication.Create();
  2. app.RegisterService(
  3. "service-a",
  4. serviceBuilder =>
  5. {
  6. serviceBuilder.RegisterStateStore(
  7. context =>
  8. {
  9. return new MultiStateStore(context.InstanceId);
  10. });
  11. });
  12. app.Run();
  13. class MultiStateStore : IStateStore
  14. {
  15. private readonly string instanceId;
  16. public MultiStateStore(string instanceId)
  17. {
  18. this.instanceId = instanceId;
  19. }
  20. // ...
  21. }