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. Golang中的匿名函数(闭包)

    GO语言的匿名函数就是闭包,以下是<GO语言编程>中对闭包的解释 基本概念闭包是可以包含自由(未绑定到特定对象)变量的代码块,这些变量不在这个代码块内或者任何全局上下文中定义,而是在定义代 ...

  2. vs2017新建一个空项目

    我们会发现VS2017的控制台程序创建之后会有一些头文件这和之前的VS的版本不一样之前的都可以选择空项目来避免,下面我们就来介绍方法: 首先我们不要创建新的控制台项目,而是创建桌面向导: 然后我们就可 ...

  3. Centos 7 Samba服务安装

    Centos 7 Samba服务安装搭建Samba服务器是为了实现Linux共享目录之后,在Windows可以直接访问该共享目录. 查看是已安装samba包: rpm -qa | grep samba ...

  4. C#将html table 导出成excel实例

    public void ProcessRequest (HttpContext context) { string elxStr = "<table><tbody>& ...

  5. html和css牛刀小试

    html和css网上教程很多,这里我也给大家一个网址:https://www.cnblogs.com/majj/ 今天心血来潮就模仿着小米的官网写了部分代码,效果图如下:(本人故意加了个华为广告栏在最 ...

  6. 度限制MST

    POJ1639 顶点度数限制的最小生成树 做法:首先把和顶点相连的X条边全部删掉 得到顶点和 X个连通块 然后求出这X个连通块的MST 再把X条边连接回去这样我们就首先求出了X度MST 知道了X度MS ...

  7. MST-kruskal ElogE+V

    hdu 1233 #include<stdio.h> #include<algorithm> using namespace std; struct dis { int a, ...

  8. CentOS下phpMyAdmin安装

    1.phpMyAdmin官网下载https://www.phpmyadmin.net/downloads/ 2.下载程序包 wget https://files.phpmyadmin.net/phpM ...

  9. 一分钟 解决Tomcat端口 占用问题

    打开 cmd命令 在 命令界面中输入 netstat -ano|findstr 8080 使用 命令 taskill /pid 端口号  /f    结束占用

  10. Python 3标准库 第十四章 应用构建模块

    Python 3标准库 The Python3 Standard Library by  Example -----------------------------------------第十四章   ...