合成后如何更改MEF中的一部分合成?

| 我已将我的应用设置为具有可发现的安全服务(
ISecurityService
),该服务具有单一方法
IPrincipal GetPrincipal()
。实现者可以自由决定如何获取主体(通过域登录,数据库等)。因此,我的应用程序然后包含一些部分,这些部分在启动时根据用户所处的角色来确定,例如,我导入的界面部分如下所示:
[Import]
public ISecurityService SecurityService {
    get; set;
}
[ImportMany]
public IEnumerable<ISectionPanel> ImportedPanels {
    get; set;
}
public ObservableCollection<ISectionPanel> Panels {
    get; set;
}
public void OnImportsSatisfied() {
    Panels.Clear();
    IPrincipal p = Thread.CurrentPrincipal;
    foreach (ISectionPanel sp in ImportedPanels.Where(sp => sp.RequiredRole == null || p.IsInRole(sp.RequiredRole))) {
        Panels.Add(p);
    }
}
不要过多地专注于实现,这将在以后更改为批注,但是,让我无法自拔的重要之处在于,部件的构成是在设置安全主体之前进行的。这意味着我现在遇到了麻烦。 现在,我通过在导入上使用
Lazy<T>
解决了影响链接发生的问题,但是,如果部件的另一个实现者忘记使用
Lazy<T>
,则可能会触发链接的负载并导致应用程序失败。 其他人用什么来克服这种情况? 以前,我有一个统一性,我只需使用ѭ5即可通过一种更为手动的方式进行控制,我现在尝试使用“正式” MEF编写应用程序,因为框架附带了该功能,因此我不再需要担心统一性。 理想情况下,我想做的是。 在启动之前先手动创建零件 手动创建一个合成容器,添加我的预制零件(例如,统一为
RegisterInstance<T>(T t)
) 使用文档中所示的常用组成方法查找剩余零件。     
已邀请:
您可以分两个阶段初始化应用程序:
public static void Main(string[] args)
{
    using (var container = new CompositionContainer(...))
    {
        // phase 1: compose security service and initialize principal
        var securityService = container.GetExportedValue<ISecurityService>();
        securityService.InitializePrincipal();

        // phase 2: compose the rest of the application and start it
        var form = container.GetExportedvalue<MainForm>();
        Application.Run(form);
    }
}
    
在MEF中,或多或少地对应于
RegisterInstance
是be9ѭ方法。如果主机在不使用MEF的情况下创建了安全服务,这将起作用。由于您仍然想使用MEF发现安全服务,因此Wim提出的建议可能是一个很好的解决方案。     

要回复问题请先登录注册