我已经开始与 MEF 合作。在我的应用程序中,我有一些模型的工厂。我的工厂有 2 种创建方法;一个接受名称作为参数,另一个接受类型。
[Export(typeof(IFactory))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyFactory : IFactory
{
public IModel Create(String name) {...}
public IModel Create(Type type) {...}
}
public class Foo
{
[Import(typeof(IFactory))]
public IFactory Factory { get; set; }
public Foo()
{
IModel modelByName = Factory.Create("name");
IModel modelByType = Factory.Create(typeof(Foo));
}
}
目前我必须导入一个工厂,然后在工厂对象上调用 create 来获取模型。现在我想知道是否有办法直接导入模型,例如:
[Import(typeof(IModel), Name:"Name")]
public IModel Model { get; set; }
编辑 - - - - - - - - - - - - - - - - - - - - - - - - - --
目标是替换如下内容:
public class Foo
{
[Import(typeof(IFactory))]
public IFactory Factory { get; set; }
public IModel Model { get; set; }
public IModel Model1 { get; set; }
public Foo()
{
Model = Factory.Create("Foo");
Model1 = Factory.Create(typeof(Foo1));
}
}
像这样的东西:
public class Foo
{
//Should internal import a IFactory(singeleton) object
//and call the Create(name:String) method on it
[Import(typeof(IModel), Name:"Foo")]
public IModel Model { get; set; }
//Should internal import a IFactory(singeleton) object
//and call the Create(type:Type) method on it
[Import(typeof(IModel), Type: typeof(Foo1))]
public IModel Model1 { get; set; }
}