I am using MEF as DI container and the problem is that I want to import specific part from multiple parts.
For example, I have following codes :
public interface IService
{
void Send();
}
[Export(typeof(IService))]
public class Service : IService
{
public void Send()
{
Console.WriteLine("Service.Send");
}
}
[Export(typeof(IService))]
public class FakeService : IService
{
public void Send()
{
Console.WriteLine("FakeService.Send");
}
}
[Import]
public IService Service { get; set; } // ---> let's say I want to use FakeService
Is there any solution?
Thanks in advance
You can export metadata with your class, here’s an example:
Given that contract and those example implementations, we can import out types as
Lazy<T, TMetadata>whereby we can define a metadata contract:You don’t need to worry about creating an implementation of the metadata, as MEF will project any
ExportMetadataattribute values as concrete implementation ofTMetadata, which in our example isINamedMetadata. With the above, I can create the following example:In that sample class, I am importing many instances, as
Lazy<ILogger, INamedMetadata>instances. UsingLazy<T,TMetadata>allows us to access the metadata before accessing the value. In the example above, I’m using thenameargument to select the appropriate logger to use.If it is not right to instantiate the class on import, you can use an
ExportFactory<T,TMetadata>which allows you to spin up instances of your types on demand. (ExportFactoryis included in the Silverlight version of .NET 4.0, but Glenn Block did throw the source code on codeplex for Desktop/Web use.I hope that helps.