Unboxing Instances of Different Types with a Generic Type Parameter that Implements an Interface










1















I am working on an abstraction for a variation on a key-value store style API where I have the following interfaces (simplified for clarity).



type IValue =
abstract member Id: int64

type IKey<'value when 'value :> IValue> = interface end

type IKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
abstract member Generate: 'value -> 'key

type IKeyValueStore<'value when 'value :> IValue> =
abstract member Store: 'value -> unit
abstract member Get: int64 -> 'value option
abstract member Find<'key when 'key :> IKey<'value>> : 'key -> 'value option


Basically, each value can be looked up by multiple keys, and the keys for each value are generated by IKeyGenerators. When I call Store on the IKeyValueStore, I want to find all the key generators for the given value, run each of them, and store each key for the value so it can then be retrieved by any of those keys.



My problem is that, while I can reflectively discover all implementations of IKeyGenerator that have a 'value type parameter that matches the 'value type for this IKeyValueStore, I can't safely unbox them to a consistent type. I tried unboxing them all to IKeyGenerator<'value, IKey<'value>>, but this doesn't work if the concrete implementations don't explicitly implement the interface that way. If they implement the interface referring to a specific implementation of IKey, the unboxing fails.



I then tried introducing a simplified IKeyGenerator<'value> interface that defined the Generate method as simply returning IKey<'value> instead of 'key :> IKey<'value>, which solves the problem with unboxing all the implementations, but I then run into problems downstream with not knowing the actual type of the key (for example, in order to do the Find when there are multiple possible keys for this value).



Is there some way I can safely obtain a list of IKeyGenerator instances for different IKey implementations, provided that they all implement IKey<'value> for the same type of value?










share|improve this question


























    1















    I am working on an abstraction for a variation on a key-value store style API where I have the following interfaces (simplified for clarity).



    type IValue =
    abstract member Id: int64

    type IKey<'value when 'value :> IValue> = interface end

    type IKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
    abstract member Generate: 'value -> 'key

    type IKeyValueStore<'value when 'value :> IValue> =
    abstract member Store: 'value -> unit
    abstract member Get: int64 -> 'value option
    abstract member Find<'key when 'key :> IKey<'value>> : 'key -> 'value option


    Basically, each value can be looked up by multiple keys, and the keys for each value are generated by IKeyGenerators. When I call Store on the IKeyValueStore, I want to find all the key generators for the given value, run each of them, and store each key for the value so it can then be retrieved by any of those keys.



    My problem is that, while I can reflectively discover all implementations of IKeyGenerator that have a 'value type parameter that matches the 'value type for this IKeyValueStore, I can't safely unbox them to a consistent type. I tried unboxing them all to IKeyGenerator<'value, IKey<'value>>, but this doesn't work if the concrete implementations don't explicitly implement the interface that way. If they implement the interface referring to a specific implementation of IKey, the unboxing fails.



    I then tried introducing a simplified IKeyGenerator<'value> interface that defined the Generate method as simply returning IKey<'value> instead of 'key :> IKey<'value>, which solves the problem with unboxing all the implementations, but I then run into problems downstream with not knowing the actual type of the key (for example, in order to do the Find when there are multiple possible keys for this value).



    Is there some way I can safely obtain a list of IKeyGenerator instances for different IKey implementations, provided that they all implement IKey<'value> for the same type of value?










    share|improve this question
























      1












      1








      1








      I am working on an abstraction for a variation on a key-value store style API where I have the following interfaces (simplified for clarity).



      type IValue =
      abstract member Id: int64

      type IKey<'value when 'value :> IValue> = interface end

      type IKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
      abstract member Generate: 'value -> 'key

      type IKeyValueStore<'value when 'value :> IValue> =
      abstract member Store: 'value -> unit
      abstract member Get: int64 -> 'value option
      abstract member Find<'key when 'key :> IKey<'value>> : 'key -> 'value option


      Basically, each value can be looked up by multiple keys, and the keys for each value are generated by IKeyGenerators. When I call Store on the IKeyValueStore, I want to find all the key generators for the given value, run each of them, and store each key for the value so it can then be retrieved by any of those keys.



      My problem is that, while I can reflectively discover all implementations of IKeyGenerator that have a 'value type parameter that matches the 'value type for this IKeyValueStore, I can't safely unbox them to a consistent type. I tried unboxing them all to IKeyGenerator<'value, IKey<'value>>, but this doesn't work if the concrete implementations don't explicitly implement the interface that way. If they implement the interface referring to a specific implementation of IKey, the unboxing fails.



      I then tried introducing a simplified IKeyGenerator<'value> interface that defined the Generate method as simply returning IKey<'value> instead of 'key :> IKey<'value>, which solves the problem with unboxing all the implementations, but I then run into problems downstream with not knowing the actual type of the key (for example, in order to do the Find when there are multiple possible keys for this value).



      Is there some way I can safely obtain a list of IKeyGenerator instances for different IKey implementations, provided that they all implement IKey<'value> for the same type of value?










      share|improve this question














      I am working on an abstraction for a variation on a key-value store style API where I have the following interfaces (simplified for clarity).



      type IValue =
      abstract member Id: int64

      type IKey<'value when 'value :> IValue> = interface end

      type IKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
      abstract member Generate: 'value -> 'key

      type IKeyValueStore<'value when 'value :> IValue> =
      abstract member Store: 'value -> unit
      abstract member Get: int64 -> 'value option
      abstract member Find<'key when 'key :> IKey<'value>> : 'key -> 'value option


      Basically, each value can be looked up by multiple keys, and the keys for each value are generated by IKeyGenerators. When I call Store on the IKeyValueStore, I want to find all the key generators for the given value, run each of them, and store each key for the value so it can then be retrieved by any of those keys.



      My problem is that, while I can reflectively discover all implementations of IKeyGenerator that have a 'value type parameter that matches the 'value type for this IKeyValueStore, I can't safely unbox them to a consistent type. I tried unboxing them all to IKeyGenerator<'value, IKey<'value>>, but this doesn't work if the concrete implementations don't explicitly implement the interface that way. If they implement the interface referring to a specific implementation of IKey, the unboxing fails.



      I then tried introducing a simplified IKeyGenerator<'value> interface that defined the Generate method as simply returning IKey<'value> instead of 'key :> IKey<'value>, which solves the problem with unboxing all the implementations, but I then run into problems downstream with not knowing the actual type of the key (for example, in order to do the Find when there are multiple possible keys for this value).



      Is there some way I can safely obtain a list of IKeyGenerator instances for different IKey implementations, provided that they all implement IKey<'value> for the same type of value?







      .net generics f#






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 15:33









      Aaron M. EshbachAaron M. Eshbach

      4,907918




      4,907918






















          1 Answer
          1






          active

          oldest

          votes


















          3














          I would recommend a two-tier implementation of the key generators: a base class that implements IKeyGenerator, but itself has more concrete type parameters, constrained in the way you have there:



          type IKeyGenerator<'value when 'value :> IValue> =
          abstract member Generate: 'value -> IKey<'value>

          [<AbstractClass>]
          type KeyGeneratorBase<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
          abstract member Generate: 'value -> 'key

          interface IKeyGenerator<'value> with
          override this.Generate v = this.Generate v :> _


          Then have specific implementations inherit from KeyGeneratorBase.



          This way, the implementations can have their concrete types to work with, and the consumer will have the narrow types that it expects.



          Or, alternatively (and I much prefer this way), have a function to create IKeyGenerators:



          let mkKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> (gen : 'value -> 'key) = 
          new IKeyGenerator<_> with
          member this.Generate v = gen v :> _




          P.S. I know this is not what you asked for, but I must warn against excessive use of reflection and classes. This never ends well. Consider a more functional, idiomatic approach.






          share|improve this answer

























          • I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

            – Aaron M. Eshbach
            Nov 15 '18 at 16:42











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53303693%2funboxing-instances-of-different-types-with-a-generic-type-parameter-that-impleme%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          I would recommend a two-tier implementation of the key generators: a base class that implements IKeyGenerator, but itself has more concrete type parameters, constrained in the way you have there:



          type IKeyGenerator<'value when 'value :> IValue> =
          abstract member Generate: 'value -> IKey<'value>

          [<AbstractClass>]
          type KeyGeneratorBase<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
          abstract member Generate: 'value -> 'key

          interface IKeyGenerator<'value> with
          override this.Generate v = this.Generate v :> _


          Then have specific implementations inherit from KeyGeneratorBase.



          This way, the implementations can have their concrete types to work with, and the consumer will have the narrow types that it expects.



          Or, alternatively (and I much prefer this way), have a function to create IKeyGenerators:



          let mkKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> (gen : 'value -> 'key) = 
          new IKeyGenerator<_> with
          member this.Generate v = gen v :> _




          P.S. I know this is not what you asked for, but I must warn against excessive use of reflection and classes. This never ends well. Consider a more functional, idiomatic approach.






          share|improve this answer

























          • I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

            – Aaron M. Eshbach
            Nov 15 '18 at 16:42
















          3














          I would recommend a two-tier implementation of the key generators: a base class that implements IKeyGenerator, but itself has more concrete type parameters, constrained in the way you have there:



          type IKeyGenerator<'value when 'value :> IValue> =
          abstract member Generate: 'value -> IKey<'value>

          [<AbstractClass>]
          type KeyGeneratorBase<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
          abstract member Generate: 'value -> 'key

          interface IKeyGenerator<'value> with
          override this.Generate v = this.Generate v :> _


          Then have specific implementations inherit from KeyGeneratorBase.



          This way, the implementations can have their concrete types to work with, and the consumer will have the narrow types that it expects.



          Or, alternatively (and I much prefer this way), have a function to create IKeyGenerators:



          let mkKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> (gen : 'value -> 'key) = 
          new IKeyGenerator<_> with
          member this.Generate v = gen v :> _




          P.S. I know this is not what you asked for, but I must warn against excessive use of reflection and classes. This never ends well. Consider a more functional, idiomatic approach.






          share|improve this answer

























          • I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

            – Aaron M. Eshbach
            Nov 15 '18 at 16:42














          3












          3








          3







          I would recommend a two-tier implementation of the key generators: a base class that implements IKeyGenerator, but itself has more concrete type parameters, constrained in the way you have there:



          type IKeyGenerator<'value when 'value :> IValue> =
          abstract member Generate: 'value -> IKey<'value>

          [<AbstractClass>]
          type KeyGeneratorBase<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
          abstract member Generate: 'value -> 'key

          interface IKeyGenerator<'value> with
          override this.Generate v = this.Generate v :> _


          Then have specific implementations inherit from KeyGeneratorBase.



          This way, the implementations can have their concrete types to work with, and the consumer will have the narrow types that it expects.



          Or, alternatively (and I much prefer this way), have a function to create IKeyGenerators:



          let mkKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> (gen : 'value -> 'key) = 
          new IKeyGenerator<_> with
          member this.Generate v = gen v :> _




          P.S. I know this is not what you asked for, but I must warn against excessive use of reflection and classes. This never ends well. Consider a more functional, idiomatic approach.






          share|improve this answer















          I would recommend a two-tier implementation of the key generators: a base class that implements IKeyGenerator, but itself has more concrete type parameters, constrained in the way you have there:



          type IKeyGenerator<'value when 'value :> IValue> =
          abstract member Generate: 'value -> IKey<'value>

          [<AbstractClass>]
          type KeyGeneratorBase<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> =
          abstract member Generate: 'value -> 'key

          interface IKeyGenerator<'value> with
          override this.Generate v = this.Generate v :> _


          Then have specific implementations inherit from KeyGeneratorBase.



          This way, the implementations can have their concrete types to work with, and the consumer will have the narrow types that it expects.



          Or, alternatively (and I much prefer this way), have a function to create IKeyGenerators:



          let mkKeyGenerator<'value, 'key when 'value :> IValue and 'key :> IKey<'value>> (gen : 'value -> 'key) = 
          new IKeyGenerator<_> with
          member this.Generate v = gen v :> _




          P.S. I know this is not what you asked for, but I must warn against excessive use of reflection and classes. This never ends well. Consider a more functional, idiomatic approach.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 17:03

























          answered Nov 14 '18 at 16:49









          Fyodor SoikinFyodor Soikin

          42.9k56699




          42.9k56699












          • I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

            – Aaron M. Eshbach
            Nov 15 '18 at 16:42


















          • I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

            – Aaron M. Eshbach
            Nov 15 '18 at 16:42

















          I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

          – Aaron M. Eshbach
          Nov 15 '18 at 16:42






          I ended up going with a variation of the second solution here, where I just tag a function of 'value -> 'key with an attribute and then do the interface generation dynamically when I find that attribute. I think this will satisfy my OO consumers while making it idiomatic for F# users as well.

          – Aaron M. Eshbach
          Nov 15 '18 at 16:42




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53303693%2funboxing-instances-of-different-types-with-a-generic-type-parameter-that-impleme%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3

          Museum of Modern and Contemporary Art of Trento and Rovereto