You don't need to use reflection with MEF, you simply Export & Import to share data - the data can exist in a DLL/EXE outside of the main app. So long as MEF can compose, the data will be visible. This is what we did in another
MEF Solution[
^] where reflection was requested for a plugin system and the plugins automatically load when the DLL/EXE is dropped into the main app's folder.
So, the answer is to create a class to hold your user details in a seperate class (repository), define the
Export
with a
PartCreationPolicy(CreationPolicy.Shared)
. This will create a static/shared object. Here is an example:
public interface IUserRepository
{
string UserName { get; set; }
}
[Export(typeof(IUserRepository)),
PartCreationPolicy(CreationPolicy.Shared)]
public class UserRepository : ObservableBase, IUserRepository
{
private string userName = "**Not Set**";
public string UserName
{
get => userName;
set => Set(ref userName, value);
}
}
NOTE: The above code is not thread safe. I'll leave that up to you to implement if you require that.
Here is the
ObservableBase
class:
public abstract class ObservableBase : INotifyPropertyChanged
{
public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public bool IsInDesignMode => DesignerProperties.GetIsInDesignMode(new DependencyObject());
}
Now you
import
the
UserRepository
:
[Import(typeof(IUserRepository), RequiredCreationPolicy = CreationPolicy.Shared)]
public IUserRepository Repo { get; set; }
... and the user data is now shared whereever the above
Import
is used:
Repo.UserName = "MainUser";
No reflection coding by you is required as it is all handled by MEF. Enjoy!
PS: Yes, MEF is using reflection so you don't have to! ;)