-
18-09-2019 - |
题
我想弄清楚MEF的构造器注入属性。我不知道我该怎么告诉它加载构造函数的参数。
这是我试图加载属性
[ImportMany(typeof(BUsers))]
public IEnumerable<BUsers> LoadBUsers { get; set; }
下面是我使用导入器组件的代码。
try
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog("DI"));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
这里是我试图加载类
[Serializable]
[Export(typeof(BUsers))]
public class EditProfile : BUsers
{
[ImportingConstructor]
public EditProfile(string Method, string Version)
{
Version = "2";
Action = "Edit";
TypeName = "EditProfile";
}
解决方案
当您使用ImportingConstructor属性,参数来构造成为进口。默认情况下,你要导入(合同名称)是基于您导入到参数或属性的类型。因此,在这种情况下,为您的进口合同类型为字符串,并有第一和第二个参数之间没有真正的区别。
看起来你要使用进口提供配置值,这不一定是什么它是专为。为了得到它做你想要什么,你应该为每个参数的重写合同的名称,像这样的:
[ImportingConstructor]
public EditProfile([Import("Method")] string Method, [Import("Version")] string Version)
{ }
然后你需要在容器中的方法和版本出口。这样做的一种方式就是直接添加:
var container = new CompositionContainer(catalog);
container.ComposeExportedValue("Method", "MethodValue");
container.ComposeExportedValue("Version", "2.0");
container.ComposeParts(this);
(注意,ComposeExportedValue实际上是对静态AttributedModelServices类中定义的扩展方法。)
如果你想读从某种类型的配置文件这些值,你可以创建自己的出口供应商,其读取配置和它作为出口容器提供的值。
来处理这将是刚刚导入的名字提供给配置值的访问接口,并且让你从构造的身体所需要的值的另一种方式。
其他提示
我喜欢丹尼尔的溶液;然而,只有一件事我看到的是演员之间的参数名称的紧耦合(谁创造CompopositionContrainer()),并与定制CTOR [ImportingConstructor]部分出口。例如,“办法”有两个可以在这两个地方相匹配。这使得很难保持出口的一部分,如果演员和出口部分是差的项目。
如果它是可能的,我将第二CTOR添加到导出部分类。例如:
[Export(typeof(BUsers))]
public class EditProfile : BUsers
{
[ImportingConstructor]
public EditProfile(EditProfileParameters ctorPars)
: this(ctorPars.Method, ctorPars.Version) {}
public EditProfile(string Method, string Version)
{
Version = "2";
Action = "Edit";
TypeName = "EditProfile";
}
类EditProfileParameters的应该是直接的:方法和版本的两个属性:
[Export]
public class EditProfileParameters{
public string Method { get; set; }
public string Version { get; set; }
}
的关键点是对导出属性添加到类。然后MEF应该能够映射这个类EditProfile的CTOR的参数。
下面是例如,要添加导出部到容器:
var container = new CompositionContainer(catalog);
var instance1 = new EditProfileParameters();
// set property values from config or other resources
container.ComposeExportedValue(instance1);
container.ComposeParts(this);
虽然太迟了,这里是一个利用MEF的鲜为人知的功能的另一种方法:房产出口
public class ObjectMother
{
[Export]
public static EditProfile DefaultEditProfile
{
get
{
var method = ConfigurationManager.AppSettings["method"];
var version = ConfigurationManager.AppSettings["version"];
return new EditProfile(method,version);
}
}
}
,不需要为用法ObjectMother为此工作,并且没有属性是必需上EditProfile。