ekolis
ekolis

Reputation: 6786

Is it possible to have MEF instantiate a class multiple times?

So let's say I have an interface IMultiplayerService and several classes implementing it, such as a Pbw3 class. Now Pbw3 represents a particular server app, but there could be multiple instances of that server - one that I run, one that a friend runs, etc.

Is there any way to have MEF instantiate Pbw3 multiple times? Or is it limited to one instance of each imported class?

I was thinking one workaround might be to create a factory class for each multiplayer server class, and have MEF create those instead, but I was hoping there's an easier way...

Upvotes: 0

Views: 69

Answers (1)

Adi Lester
Adi Lester

Reputation: 25201

Have a look at MEF's ExportFactory.

You can import ExportFactory<IMultiplayerService> and then create new instances as required:

[Import]
public ExportFactory<IMultiplayerService> MultiplayerServiceFactory { get; set; }
var instance1 = MultiplayerServiceFactory.CreateExport().Value
var instance2 = MultiplayerServiceFactory.CreateExport().Value

Upvotes: 1

Related Questions