Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DependencyAttribute class in F#

I am working though Petzold's Creating Mobile Apps Using Xamarin Forms book, translating the C# code into F# where the F# code is not available on GitHub (he stopped posting FS after chapter 7). In chapter 9, page 189, he makes use of the Dependency attribute like this:

[assembly: Dependency(typeof(DisplayPlatformInfo.iOS.PlatformInfo))]
namespace DisplayPlatformInfo.iOS
{
  public interface IPlatformInfo
 {
 string GetModel();
 string GetVersion();
 }
  using System;
 using UIKit;
 using Xamarin.Forms;
  public class PlatformInfo : IPlatformInfo
 {
 UIDevice device = new UIDevice();
 //etc...

I want to do the equivalent in F#. I created the type and the only place I can add that attribute is at a generic do() statement:

type PlatformInfo () =
    [<assembly: Dependency(typeof(Greetings.iOS.PlatformInfo))>]
    do()

    interface IPlatformInfo with
        member this.GetModel () = 
            let device = new UIDevice()
            device.Model.ToString()
        member this.GetVersion () = 
            let device = new UIDevice()
            String.Format("{0} {1}", device.SystemName, device.SystemVersion)

The problem is that I get a

warning: attributes are ignored in this construct.

How should I be placing this attribute into the type?

like image 497
Jamie Dixon Avatar asked Jun 27 '26 11:06

Jamie Dixon


2 Answers

Assembly level attributes in F# need to be a in module, at the top level.

I would translate the C# above as:

namespace rec DisplayPlatformInfo.iOS

// Make a module specifically for this attribute
module DisplayPlatformAssemblyInfo =
    [<assembly: Dependency(typeof(Greetings.iOS.PlatformInfo))>]
    do ()

type IPlatformInfo =
    abstract member GetModel : unit -> string
    abstract member GetVersion : unit -> string

// ... Implement your type, etc
like image 128
Reed Copsey Avatar answered Jul 01 '26 10:07

Reed Copsey


Since it is an assembly attribute, it should be place at the top level of a module instead of in a type. The following should be working:

[<assembly: Dependency(typeof(Greetings.iOS.PlatformInfo))>]
do ()

type PlatformInfo () =
   // ...