tags:

views:

28

answers:

1

Using MEF, I know you can do this to import your interface:

class MyClass

{

[Import(typeof(IUser))]

private IUser m_userName;

}

Can I do something similar but within the method? For example, this below does not compile:

class MyClass

{

public void DoWork()

{

      [Import(typeof(IUser))]

      IUser userName;


      userName.dosoething();

}

}

A: 

As you've seen, you can't use Imports in that way. In fact you can't ever use an attribute inside method code, so there would be no way to use the attribute in a method.

You can however find exports of a given type by using the container, something like this:

IUser userName = (IUser)container.GetExports(typeof(IUser), null, null).FirstOrDefault();
Simon Steele