0

짧은 질문 : Unity의 Autofac 설명서 섹션 Passing Parameters to Resolve에 설명 된대로 TypedParameter과 동일한 기능을 어떻게 수행 할 수 있습니까?Autofac TypedParameter Unity 대체품

일부 배경 : 기본 클래스의 생성자 매개 변수의 이름을 바꾸는 상속 된 클래스를 해결해야합니다. 이 매개 변수는 해석 될 수 없으며 전달되어야합니다. 상속 된 클래스는 해결할 수있는 유형과 하나의 기본 클래스 생성자 매개 변수 만 가질 수 있습니다.

종류와 관련, 제프

+1

[주입 생성자에 런타임 데이터 주입 금지] (https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99). 이미 눈치 챘을 때 모든 종류의 합병증이 발생합니다. – Steven

+0

@ 스 베인 실제 문제에 대한 해결책을 찾고있는 중에 실제로 오늘 일찍 게시물을 읽었지만 좋은 해결책을 찾지 못했습니다. 내 질문은 이전에 게시 한 다른 질문과 관련이 있습니다. http://stackoverflow.com/questions/42908224/initialize-hierarchical-tree-viewmodels-with-unity 저는 ​​VM에서 모델을 랩핑하는 것이 좋은 습관이라고 생각합니다. 나는 INodeVMFactory를 만들 수 있었지만 그때 같은 기본 문제를 돌리고 있습니다. 우리는 다른 컨테이너로 전환 할 수도 있지만 먼저 문제에 대해 잘 알아야합니다. –

답변

0

당신은 만들 수 있습니다 자신의이 같은 TypedParameter :

internal class Program 
{ 
    static void Main(string[] args) 
    { 
     var container = new UnityContainer(); 
     container.RegisterType<IInterface, Implementation>(); 

        // this will be created with this MyLogger instance 
     var instance = container.Resolve<IInterface>(new TypedParameter(typeof(ILogger), new MyLogger())); 
    } 
} 

internal class TypedParameter : ResolverOverride 
{ 
    private readonly Type _type; 
    private readonly InjectionParameterValue _value; 

    public TypedParameter(Type type, object value) 
    { 
     _type = type; 
     _value = InjectionParameterValue.ToParameter(value); 
    } 

    public override IDependencyResolverPolicy GetResolver(IBuilderContext context, Type dependencyType) 
    { 
     ConstructorArgumentResolveOperation currentOperation = context.CurrentOperation as ConstructorArgumentResolveOperation; 
     if (currentOperation != null) 
     { 
      var parameter = currentOperation.TypeBeingConstructed.GetConstructors().Single().GetParameters().Single(x => x.Name == currentOperation.ParameterName); 
      if (parameter.ParameterType == _type) 
       return _value.GetResolverPolicy(dependencyType); 
     } 

     return null; 
    } 
} 

// note that this is not registered with unity, is has to come from TypedParameter 
internal class MyLogger : ILogger 
{ 
} 

internal interface ILogger 
{ 
} 

internal interface IInterface 
{ 
} 

internal class Implementation : IInterface 
{ 
    public Implementation(ILogger logger) 
    { 
    } 
} 

하지 생산 준비,하지만 구성 유형이 하나의 생성자가있는 경우가 작동합니다. 그러나 이러한 재정의는 하나의 호출에서 생성 된 모든 종속성에 대해 작동하므로주의해야합니다.