开发者

How to tell MEF to re-create object?

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, Messa开发者_StackOverflow中文版ge 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:

[Export(typeof(IContextManager)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ContextManager : IContextManager
{
   ...
}

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.


You can make the part's creation be "NonShared" by setting it on a PartCreationPolicyAttribute on the exported class, or the RequiredCreationPolicy property of an ImportAttribute.

This will create a new instance of the class with the export every time an import is satisfied. If this isn't exactly what you want, you may want to look at ExportFactory or scoped containers. However if you are using the .NET 4 version of MEF, ExportFactory isn't supported and you have to do a lot more work for scoping. You can get a preview of the next version of MEF at mef.codeplex.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜