gpt4 book ai didi

c# - MEF - 我可以创建实例并让它们在 MEF 内自动组合吗?

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:43 27 4
gpt4 key购买 nike

据我所知,为了使导入/导出属性相互正确连接,我必须对具有这些属性的每个新实例调用 compositionContainerInstance.Compose(...)

是否可以自动发生这种情况,这样我就不必在每次创建某个可组合类的新实例时都这样做?

这将是一个例子,虽然很长,但它抽象了我遇到的问题。

public class Worker1
{
[Import(typeof(IDataProvider))]
public IDataProvider DataProvider;

public Worker2 second;
//use data provider to perform logic
}

public class Worker2
{
[Import(typeof(IDataProvider))]
public IDataProvider DataProvider;

//use data provider to perform logic
}

[Export(typeof(IDataProvider))]
public class GeoDataProvider : IDataProvider
{
//implements logic
}

public class Container
{
private Worker1 t1;
public void Init()
{
AggregateCatalog cat = new AggregateCatalog();
cat.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
cat.Catalogs.Add(new DirectoryCatalog("."));

CompositionContainer c = new CompositionContainer(cat);
c.ComposeParts(new GeoDataProvider(), this);
}

public void PerformLogic()
{
t1 = new Worker1;
//here it fails because I need c.ComposeParts(t1):
t1.DoSomethingWithProvider();
//but even if I do c.ComposeParts(t1), still the t1.second.DataProvider will be null
//how to avoid this?
}
}

我希望有一种方法可以自由创建 Worker1/Worker2 的新实例,而无需知道它们必须在使用前组合。可行吗?

最佳答案

必须有人知道他们需要镇定。

如果您要自由创建 Worker1 和 Work2 实例而不是让 MEF 创建它们,那么您还必须给 MEF 一个机会来满足新实例的导入,或者正如您所发现的,IDataProvider 字段永远不会被填充出。

这是一个示例,您只需让 MEF 根据需要创建类。只需一次“ComposeParts”调用即可完成所有设置。

[Export]
public class Worker1
{
[Import]
public IDataProvider DataProvider;

[Import]
public Worker2 second;

//use data provider to perform logic
public void DoSomethingWithProvider() {
}
}

[Export]
public class Worker2
{
[Import]
public IDataProvider DataProvider;

//use data provider to perform logic
}

[Export( typeof( IDataProvider ) )]
public class GeoDataProvider : IDataProvider
{
//implements logic
}

public class Container
{
[Import]
private Worker1 t1;

public void Init()
{
AggregateCatalog cat = new AggregateCatalog();
cat.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
cat.Catalogs.Add( new DirectoryCatalog( "." ) );

CompositionContainer c = new CompositionContainer( cat );
c.ComposeParts( this );
}

public void PerformLogic()
{
t1.DoSomethingWithProvider();
}
}

关于c# - MEF - 我可以创建实例并让它们在 MEF 内自动组合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4441074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com