I’m using mef to create WCF web services. This is how service looks:
[Export]
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MobileService
{
[Import]
public IEmailService EmailService { get; set; }
[Import]
public ILoggerService LoggerService { get; set; }
[Import]
public IContextManager ContextManager { get; set; }
This is how code to retreive service instance looks:
// Get Service instace via MEF
public object GetInstance(InstanceContext instanceContext, Message message)
{
var lazyInstance = Container.GetExports(ServiceType, null, null).FirstOrDefault();
var instance = lazyInstance.Value;
return instance;
}
MEF creates EmailService, LoggerService and this if fine, they live happily while service lives.
Now, ContextManager is different animal. In GetInstance – I really like to “kill” it and re-create. ContextManager studies URL and headers during construction and populates “context”. With code like I have – it is created first time and never get’s destroyed. How to change this behavior?
Thanks!
On your export of the implementation of IContextManager, you need to mark the export with the non-shared part creation policy. For example:
This will inform MEF that it should create a new instance of the export every time it satisfies an import. By default MEF uses CreationPolicy.Shared which will create just a single exported value (a singleton), which is probably what you want for the Email and Logging implementations.