开发者

Does MEF Support Customized CTOR?

It looks like that MEF framework creates objects which have default CTOR. How about customized CTOR, or Constructor with parameters? For example:

[Export (typeof(IInterface1))]
public class MyClass : IInterface1
{
    public MyClass(int id) {....}
    ....
}

If not, one way I can think is to pass object as parameters to CTOR. For example:

public Interface IParameterID { public int 开发者_如何学GoId { get; private set; } ... }

Then the CTOR will be:

public MyClass([Import(typeof(IParameter))] IParameterID id)
{ ... }

Not sure if it is possible to add attribute to CTOR's parameters? And the next question is that if MEF will automatically create an instance of IParameter and inject it to the CTOR's parameter?


Yes, this is possible. Just put an [ImportingConstructorAttribute] on the constructor you would like to use. The parameters will automatically be treated as imports, but if you need to change the contract name on them you can also put an import attribute on them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜