2010-08-19 85 views
1

將調用對象導入到構造函數參數中我正在將一些代碼從專有系統轉換爲MEF,這與MEF執行的操作類似,我對如何使用MEF我會完成我最近遇到的以下問題。使用[ImportingConstructor]使用MEF

我有一個看起來像這樣一個典型的實體對象:

public class Account { 

    [Import] 
    public IAccountServerService { get; set; } 
} 

而且需要在被導入到上述實體對象服務對象:

public class AccountServerService : IAccountServerService { 

    [ImportingConstructor] 
    public AccountServerService (Account account) { ... } 
} 

要把它放到單詞我需要account參數傳遞給AccountServerService構造函數實例作爲調用Account對象的對象。因此,它像這樣:

public class Account { 

    public IAccountServerService { get { return new AccountServerService (this); } } 
} 

請讓我知道,如果這個情況是可能的,或者如果我需要修改我的服務接口,在這種情況下。

回答

0

所以MEF支持循環依賴,但它們都必須是屬性導入,它們都不能是構造函數導入。因此,從MEF的角度來看,以下內容應該可以發揮作用,當然我不確定這種方法是否受到其他一些限制。

public class AccountServerService : IAccountServerService { 
    [Import] 
    public Account Account { get; set; } 

    public AccountServerService() { ... } 
} 

public class Account { 
    [Import] 
    public IAccountServerService { get; set; } 
} 
0

我不確定在MEF中是否存在相互遞歸合同。我將它列入以下不需要相互遞歸的服務合同。

interface IAccountFactory { 
    Account CreateAccount(IAccountServerService service); 
} 

[Export(typeof(IAccountFactory))] 
sealed class AccountFactory { 
    Account CreateAccount(IAccountServerService service) { 
    return new Account(service); 
    } 
} 

class Account { 
    Account(IAccountServerService service) { 
     ... 
    } 
} 
+0

我想我是一個小溪出來然後一個槳。因爲我喜歡這樣做,但是使用Entity Framework可以防止這種情況發生。 – 2010-08-19 16:02:52

1

如果您可以更改循環依賴鏈中的一個導入爲惰性導入,它應該可以工作。例如:

[Import] 
public Lazy<IAccountServerService> { get; set; }