Skip to content

Inject existing object into MEF2 #27324

Closed

Description

@gthvidsten

Say I have an object:

IMyObject obj = SomeFactory.CreateMyObject();
obj.NeedsSomeConfiguration()
    .NeedsMoreConfiguration();

and I've set up MEF to use the current assembly (of which IMyObject is defined)

ContainerConfiguration containerConfig = new ContainerConfiguration()
    .WithAssembly(Assembly.GetExecutingAssembly())

How can I inject the specific instance of obj into this configuration so that I can do the following in an exported class

[Export(typeof(IOtherObject))]
public class OtherObject : IOtherObject
{
    [Import] public IMyObject MyObject { get; set; }
}

Activity

  1. transferred this issue fromdotnet/corefxon Jan 31, 2020
  2. added this to the Future milestone on Jan 31, 2020
  3. added
    untriaged
    on Feb 23, 2020
  4. CZEMacLeod commented on Mar 30, 2020

    @CZEMacLeod

    I'm fairly sure this is partially answered in #29400 by @nblumhardt
    The 4 files in Microsoft.Composition.Demos.ExtendedPartTypes give you the ability.
    It would be nice if these were bundled up and either included in one of the existing System.Composition.* packages or a new System.Composition.??? package.

    Regardless, with the extensions available you can do

    ContainerConfiguration containerConfig = new ContainerConfiguration()
        .WithAssembly(Assembly.GetExecutingAssembly())
        .WithExport<IMyObject>(obj);
    

    or even

    ContainerConfiguration containerConfig = new ContainerConfiguration()
        .WithAssembly(Assembly.GetExecutingAssembly())
        .WithFactoryDelegate<IMyObject>(() => {
            IMyObject obj = SomeFactory.CreateMyObject();
            obj.NeedsSomeConfiguration()
                .NeedsMoreConfiguration();
            return obj;
        });
    

    or maybe

        .WithFactoryDelegate<IMyObject>(() => SomeFactory.CreateMyObject()
            .NeedsSomeConfiguration()
            .NeedsMoreConfiguration());
    
  5. removed
    untriaged
    on Jul 9, 2020
  6. tarekgh commented on Apr 14, 2022

    @tarekgh
    Member

    Closing as dups of #29400 (comment)

  7. Repository owner moved this from Future to Done in Triage POD for Reflection, META, etc.on Apr 14, 2022
  8. ghost locked as resolved and limited conversation to collaborators on May 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Compositionquestion

    Type

    No type

    Projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions