I am using Prism 4 with MEF Extensions and the MVVM pattern. During initialization in a module I call RegisterViewWithRegion(RegionNames.MyRegion, typeof(MyView)) which works perfectly when the view is constructed like this:

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MyView : UserControl
{
public MyView()
{
....

The view gets registered and everything is fine. As soon as I change the Export to a Custom Export Attribute the view can't be found anymore, although it is still in the container. This Custom Export Attribute is taken from the Stock Trader RI:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
[MetadataAttribute]
public class ViewExportAttribute : ExportAttribute, IViewRegionRegistration
{
public ViewExportAttribute()
: base(typeof(object))
{ } public ViewExportAttribute(string viewName)
: base(viewName, typeof(object))
{
ViewName = viewName;
} public string RegionName { get; set; }
public string ViewName { get; set; } }

and the interface is

public interface IViewRegionRegistration
{
string RegionName { get; }
string ViewName { get; }
}

By changing the Export Attribute to

[ViewExport(ViewName = "MyView", RegionName = RegionNames.MyRegion)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MyView : UserControl
{
public MyView()
{
....

when calling RegisterViewWithRegion it throws an error: Activation error occured while trying to get instance of type MyView, key ""

Any advice? I was looking at this part of code the whole day without finding a solution.

asked Jun 7 '11 at 20:23
okieh
148110
 
    
Later that night... I finally found out that is has something to do with this part in the Custom Export Attribute:base(typeof(object)) - but still no knowledge of how to solve the RegisterViewWithRegion problem... – okieh Jun 7 '11 at 21:14

4 Answers

Another day, another way... I will try to answer my question even though I have only limited knowledge about PRISM. In other words: I'm still learning.

The Custom Export Attribute taken from the Stock Trade RI is used by the AutoPopulateExportedViewsBehavior. This behavior adds a view to its region automatically by checking the Export Attribute for the region name then adds the view to the corresponding region. But all views with this Custom Attribute now have a contract name of "object" which makes it impossible for the ServiveLocator to find them. This Custom Attribute is for a scenario with fixed region/view links. A solution when working with a Custom Export Attribute is to get all exports of type "object" and the appropriate metadata:

MyView view;
var myList = container.GetExports<object, IViewRegionRegistration>();
foreach (Lazy<object, IViewRegionRegistration> lazy in myList)
{
if (lazy.Metadata.ViewName == "MyView")
{
view = lazy.Value as MyView;
region.Add(view);
break;
}
}

But I think when using ViewInjection and Prism Navigation it is better to just use the default [Export] attribute, then everything works smoothly.

answered Jun 8 '11 at 7:05
okieh
148110
 
 

Are you configuring the aggregate catalog in your MEF bootstrapper? If so, are you adding the assembly that contains your ViewExportAttribute and AutoPopulateExportedViewsBehavior classes? I believe this happens in the StockTraderRI's bootstrapper with this line:

this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(StockTraderRICommands).Assembly));

The StockTraderRICommands class is in the same assembly as the ViewExportAttribute and AutoPopulateExportedViewsBehavior classes.

answered Oct 18 '11 at 22:33
 
    
I had the same issue as the original asker and this was the solution. – Dylan Nov 30 '11 at 16:02

The custom export attribute passes typeof(object) to the base constructor, which changes the contract exported so that it no longer matches the import. Change it so it calls the parameterless constructor.

As far as the activation error you'll need to look at the exception in more detail. The root cause is probably there somewhere, perhaps buried under an InnerException.

answered Jun 8 '11 at 3:58
Daniel Plaisted
12.9k22747
 

I encountered exactly the same problem and it was a hard one for a MEF/PRISM beginner. okieh describes the problem very well, I just want to post an alternative solution, coming from theStocktraderUI sample application:

The solution works (/seems to work) if you want View discovery without any form of config file, etc. where you have to register your views.

1. Modify the ViewExport custom event

[Export]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
[MetadataAttribute]
public sealed class ViewExportAttribute : ExportAttribute, IViewRegionRegistration
{
public ViewExportAttribute()
: base(typeof(UserControl))
{ } public string ViewName { get { return base.ContractName; } } public string RegionName { get; set; }
}

The [Export] attribute is added and the base constructor is now called with UserControl instead of object. That way it can be discovered by MEF.

2. Modify AutoPopulateExportedViewsBehavior

[ImportMany(typeof(UserControl))]
public Lazy<UserControl, IViewRegionRegistration>[] RegisteredViews { get; set; }

The [ImportMany] attribute is added and the type of the Lazy initializiation is changed to UserControl. Now, all UserControls with IViewRegionRegistration-implementing MetaData-type are imported.

That's basically it. You can use the [ViewExport] as before. Note, that Views are limited to (sub)types of UserControl. I suppose this can be modified if you want to. And make sure your aggregate catalog imports the ViewExportAttribute and the AutoPopulateExportedViewsBehavior, as Nicolaus said...

This way, you don't need additional interfaces for your views and can still discover everything without hardcoded registration.

I hope it helps and let me know, if I missed any drawbacks of my solution.

http://stackoverflow.com/questions/6271167/prism-4-registerviewwithregion-custom-export-attributes

PRISM 4 - RegisterViewWithRegion & Custom Export Attributes的更多相关文章

  1. [转]How do you create a custom AuthorizeAttribute in ASP.NET Core?

    问: I'm trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was ...

  2. jquery 使用attr() 函数对复选框无效的原因,javascript那些事儿——properties和attributes

    复选框是网站开发的时候经常用到的网页标签之一,常见的在页面上对复选框的操作包括取值和修改复选框的状态.在jquery中,常见的操作标签的值得函数为attr,然而在操作复选框的时候,通常采用的却是pro ...

  3. Advanced Pricing - How to source Pricing Attributes using QP_CUSTOM_SOURCE.Get_Custom_Attribute_Valu

    详细内容需要参考文档:Oracle 11i Advanced Pricing-Don't Customize, Extend! utl:http://blog.csdn.net/cai_xingyun ...

  4. [翻译]NUnit---Property and Random Attributes(十四)

    小记:由于工作琐碎,没得心情翻译而且也在看<CLR vis C#>,所以断更了差不多5个月,现在继续翻译,保证会翻译完成,不会虎头蛇尾. 另:NUnit已经更新到2.6.3版本,虽然正在开 ...

  5. Collection View Programming Guide for iOS---(七)---Custom Layouts: A Worked Example

    Custom Layouts: A Worked Example Creating a custom collection view layout is simple with straightfor ...

  6. Platform Invoke

    PInvoke 允许managed code 来调用在DLL中实施的unmanged function. Platform invoke relies on metadata to locate ex ...

  7. configure.ac

    # # Copyright (C) - Tobias Brunner # Copyright (C) - Andreas Steffen # Copyright (C) - Martin Willi ...

  8. CentOS7.2非HA分布式部署Openstack Pike版 (实验)

    部署环境 一.组网拓扑 二.设备配置 笔记本:联想L440处理器:i3-4000M 2.40GHz内存:12G虚拟机软件:VMware® Workstation 12 Pro(12.5.2 build ...

  9. 所有selenium相关的库

    通过爬虫 获取 官方文档库 如果想获取 相应的库 修改对应配置即可 代码如下 from urllib.parse import urljoin import requests from lxml im ...

随机推荐

  1. c++ 用模板类实现顺序储存的线性表

    首先要注意的一点是模板类在VS中编译时如果将定义和声明分开会出现无法解析的问题,所以一般比较常见的解决的办法是将声明和定义放在同一个头文件中然后统一的调用,下面就是用模板类实现线性表的编写 #prag ...

  2. 用Python实现九九乘法表打印

    #!usr/bin/env python # -*- coding:utf-8 -*- # dic={ # 'apple':10, # 'iphon':5000, # 'wwatch Tv':3000 ...

  3. Nginx虚拟主机多server_name的顺序问题

    Nginx虚拟主机多server_name的顺序问题  大 | 中 | 小  [ 2008-11-28 11:27 | by 张宴 ] [文章作者:张宴 本文版本:v1.0 最后修改:2008.11. ...

  4. 软件测试课程--安装QTP后java环境变量冲突

    很多学习性能测试的朋友们都会有这样的问题,安装QuickTest Professional11之后,类似于eclipse.pycharm打开弹出报错窗口,命令行(CMD)也无法正常显示javac.ja ...

  5. 如何理解Hibernate的延迟加载机制?

    延迟加载就是并不是在读取的时候就把数据加载进来,而是等到使用时再加载.Hibernate使用了虚拟代理机制实现延迟加载.返回给用户的并不是实体本身,而是实体对象的代理.代理对象在用户调用getter方 ...

  6. SIM800c收发短信及AT指令

    一.sim800设备安装 淘宝搜索sim800,差不多就是这么个样子 购买之后,安装手机卡,卡的缺口向外插入,会有卡住的感觉,再按一下卡会弹出 安装usb转串口驱动(CH340),设备的指示灯先是快闪 ...

  7. 【leetcode】815. Bus Routes

    题目如下: We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. ...

  8. [Python之路] HTTP协议复习笔记

    一.HTTP请求的直观了解 我们使用网络调试助手来模拟一个TCP Server,然后使用浏览器来访问对应的IP:Port. 启动后,我们使用谷歌浏览器来访问192.168.1.8:8080: 我们可以 ...

  9. Nowcoder Typing practice ( Trie 图 )

    题目链接 题意 : 给出 n 个串.然后给出一个问询串.问你对于问询串的每一个前缀.需要至少补充多少单词才能使得其后缀包含 n 个串中的其中一个.注意 '-' 字符代表退格 分析 : 多串的匹配问询自 ...

  10. tarjan算法 习题

    dfs树与tarjan算法 标签(空格分隔): 517coding problem solution dfs树 tarjan Task 1 给出一幅无向图\(G\),在其中给出一个dfs树\(T\), ...