Dependency injection 使用[ImportingConstructor]使用MEF将调用对象导入构造函数参数

Dependency injection 使用[ImportingConstructor]使用MEF将调用对象导入构造函数参数,dependency-injection,mef,constructor-injection,Dependency Injection,Mef,Constructor Injection,我正在将我的一些代码从一个专有系统转换成MEF,该系统的功能与MEF相同,我有一个问题,关于如何完成我最近遇到的以下问题 我有一个典型的实体对象,看起来像这样: public class Account { [Import] public IAccountServerService { get; set; } } public class Account { public IAccountServerService { get { return new Accoun

我正在将我的一些代码从一个专有系统转换成MEF,该系统的功能与MEF相同,我有一个问题,关于如何完成我最近遇到的以下问题

我有一个典型的实体对象,看起来像这样:

public class Account {

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

    public IAccountServerService { get { return new AccountServerService (this); } }
}
以及需要导入到上述实体对象中的服务对象:

public class AccountServerService : IAccountServerService {

    [ImportingConstructor]
    public AccountServerService (Account account) { ... }
}
要将此转换为文字,我需要传递到
AccountServerService
构造函数实例中的
account
参数作为调用
account
对象的对象。所以它的行为是这样的:

public class Account {

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

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

请让我知道这个场景是否可行,或者我是否必须在此实例中重构我的服务接口。

我不确定在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) {
      ...
   }
}

我不确定在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) {
      ...
   }
}

所以MEF确实支持循环依赖项,但它们都必须是属性导入,两者都不能是构造函数导入。因此,从MEF的角度来看,下面的内容应该是可行的,当然我不确定这种方法是否被其他约束所阻碍

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

    public AccountServerService () { ... }
}

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

所以MEF确实支持循环依赖项,但它们都必须是属性导入,两者都不能是构造函数导入。因此,从MEF的角度来看,下面的内容应该是可行的,当然我不确定这种方法是否被其他约束所阻碍

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

    public AccountServerService () { ... }
}

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

如果您可以将循环依赖项链中的一个导入更改为延迟导入,那么它应该可以工作。例如:

[Import] 
public Lazy<IAccountServerService> { get; set; } 
[导入]
公共延迟{get;set;}

如果您可以将循环依赖项链中的一个导入更改为延迟导入,那么它应该可以工作。例如:

[Import] 
public Lazy<IAccountServerService> { get; set; } 
[导入]
公共延迟{get;set;}

那么我想我是没有桨了。因为我很想这样做,但实体框架的使用有点妨碍了这一点的实现。我想我当时是在没有划桨的情况下。因为我很想这样做,但是实体框架的使用使得这成为可能。