是否可以参数化MEF的进口? [英] Is it possible to parameterize a MEF import?

查看:155
本文介绍了是否可以参数化MEF的进口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的MEF,所以我不完全理解的能力。我想实现类似于统一的InjectionMember东西。

I am relatively new to MEF so I don't fully understand the capabilities. I'm trying to achieve something similar to Unity's InjectionMember.

让我们说我有一个导入MEF部分的类。为简单起见,我们采取以下类作为输出部分的一个例子。

Let's say I have a class that imports MEF parts. For the sake of simplicity, let's take the following class as an example of the exported part.

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class Logger {

    public string Category {
        get;
        set;
    }

    public void Write(string text) {
    }

}

public class MyViewModel {

    [Import]
    public Logger Log {
        get;
        set;
    }

}

现在我想要弄清楚的是,如果有可能指定在导入的类别属性的值。是这样的:

Now what I'm trying to figure out is if it's possible to specify a value for the Category property at the import. Something like:

public class MyViewModel {

    [MyImportAttribute(Category="MyCategory")]
    public Logger Log {
        get;
        set;
    }

}

public class MyOtherViewModel {

    [MyImportAttribute(Category="MyOtherCategory")]
    public Logger Log {
        get;
        set;
    }

}

有关目前,我在做什么是实现IPartImportsSatisfiedNotification和设置在code类别。但很明显,我宁愿整齐地在一个地方让一切。

For the time being, what I'm doing is implementing IPartImportsSatisfiedNotification and setting the Category in code. But obviously I would rather keep everything neatly in one place.

推荐答案

经过深入挖掘MEF,似乎没有办法来声明这样做。虽然你可以得到你自己的导出的属性,也没有出现任何机构得出的import属性以任何有意义的方式。

After more digging into MEF, it seems there's no way to do this declaratively. While you can derive your own export attributes, there doesn't appear to be any mechanism for deriving an import attribute in any meaningful way.

不过,设置该类别中的二传手。我不得不放弃自动物业但这就是生活。

But instead of implementing IPartImportsSatisfiedNotification, what I can do (seems obvious now) is set the category in the setter. I have to give up the automatic property but that's life.

public class MyViewModel {

    private Logger log;

    [Import]
    public Logger Log {
        get { return log; }
        set {
            log = value;
            log.Category = "MyCategory";
        }
    }

}

这篇关于是否可以参数化MEF的进口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆