문제

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는 실제로 정적 인기 Modelservices 클래스에 정의 된 확장 메소드입니다.)

어떤 종류의 구성 파일에서 이러한 값을 읽으려면 구성을 읽고 컨테이너로 내보내기로 값을 제공하는 자체 내보내기 제공자를 만들 수 있습니다.

이를 처리하는 대안적인 방법은 이름으로 구성 값에 대한 액세스를 제공하는 인터페이스를 가져오고 생성자 본문에서 필요한 값을 얻는 것입니다.

다른 팁

나는 다니엘의 해결책을 좋아한다. 그러나 내가 보는 한 가지만 한 가지만 보는 CompositionContrainer ()를 생성하는 행위자 (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);
        }
    }
}

이를 위해 Object Mother에는 사용이 필요하지 않으며 EditProfile에는 속성이 필요하지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top