Damian
Damian

Reputation: 2789

F# ImportingConstructor on primary constructor

I'm using MEF and I'd like to add an ImportingConstructorAttribute on my primary constructor. I'm using the following trick to specify an ImportingConstructor which doesn't break the encapsulation or immutability of my object.

[<Export>]
type IntradayEngine(logger:ILogger, dummy) =

    [<ImportingConstructor>] 
    new(logger) = 
        IntradayEngine(logger, None)

    member x.Start =
        ignore

    member x.Stop = 
        ignore

The only other ways I see around this are: 1. Use property injection via an ImportAttribute on a property (which requires making that property mutable and I'm not a fan of property injection) 2. Make a 'default' primary constructor and add another constructor on which I add my dependency (allows my object to be in a state I don't want)

Is there anyway to do this without breaking the accessibility, mutability, or state of my object?

Upvotes: 2

Views: 208

Answers (1)

Daniel
Daniel

Reputation: 47914

You can put an attribute on the primary constructor by placing it between the type name and the arguments.

[<Export>]
type IntradayEngine [<ImportingConstructor>](logger:ILogger) =

    member x.Start =
        ignore

    member x.Stop = 
        ignore

Upvotes: 8

Related Questions