像简单的Funq容器一样在C#中编写MEF零件 [英] composing MEF parts in C# like a simple Funq container

查看:115
本文介绍了像简单的Funq容器一样在C#中编写MEF零件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Funq 和大多数其他IoC容器中,我可以简单地通过以下操作来配置类型:

In Funq and probably most other IoC containers I can simply do this to configure a type:

container.Register<ISomeThing>(c => new SomeThing());

如何在不使用属性的情况下快速扩展MEF(或使用现有的MEF功能)以完成相同的操作.

How could I quickly extend MEF (or use existing MEF functionality) to do the same without using attributes.

这就是我认为自己可以做到的方式:

Here is how I thought I could do it:

var container = new CompositionContainer();
var batch = new CompositionBatch();
batch.AddExport<ISomeThing>(() => new SomeThing());
batch.AddExportedValue(batch);
container.Compose(batch);

使用CompositionBatch的扩展方法:

public static ComposablePart AddExport<TKey>(this CompositionBatch batch, Func<object> func)
{
    var typeString = typeof(TKey).ToString();
    return batch.AddExport(
        new Export(
            new ExportDefinition(
                typeString, 
                new Dictionary<string, object>() { { "ExportTypeIdentity", typeString } }),
            func));

}

如果以后再做:

var a = container.GetExport<ISomeThing>().Value;
var b = container.GetExport<ISomeThing>().Value;

两个实例都相同.如何强制(配置)它们为不同的实例?

Both instance are the same. How can I force (configure) them to be different instances?

如果这不是要走的路,我将如何在MEF中做到这一点?

If this is not the way to go, how would I do this in MEF?

推荐答案

如果您不想使用属性,则可以使用此技巧(基于

If you don't want to use attributes, you can use this trick (based on Mark Seemann's blogpost).

首先,创建一个像这样的通用类:

First, create a generic class like this:

[PartCreationPolicy(CreationPolicy.NonShared)]
public class MefAdapter<T> where T : new()
{
    private readonly T export;

    public MefAdapter()
    {
        this.export = new T();
    }

    [Export]
    public virtual T Export
    {
        get { return this.export; }
    }
}

现在,您可以在容器中注册所需的任何类,如下所示:

Now you can register any class you want in the container, like this:

var registeredTypesCatalog = new TypeCatalog(
    typeof(MefAdapter<Foo>),
    typeof(MefAdapter<Bar>), 
    ...);
var container = new CompositionContainer(catalog);

或者,您可以实现从 ExportProvider ,它使您可以重复使用Funq的工作方式:

Alternatively, you could implement your own export provider derived from ExportProvider, which allows you to pretty much duplicate Funq's way of working:

var provider = new FunqyExportProvider();
provider.Register<IFoo>(context => new Foo());
var container = new CompositionContainer(provider);

这篇关于像简单的Funq容器一样在C#中编写MEF零件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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