2017-05-04 1 views
3

내 데모 코드는 더 문제가없는 파생 클래스의 DerivedDecorations은 위의 경우공장 패턴 <T> 문제

에 확인할 수 없습니다

using Microsoft.Practices.Unity; 
using System; 

public interface IDecorator 
{ 
    string GetA(); 
} 

public class Decorations:IDecorator 
{ 

    public string GetA() 
    { 
     return "temp"; 
    } 
} 

public class Base 
{ 

} 

public class Derive : Base 
{ 
    [Dependency] 
    public IDecorator DerivedDecorations { get; set; } 
} 


public class Program 
{ 
    private static void Main(string[] args) 
    { 

     Base bd = new Derive(); // here is the point 

     var container = new UnityContainer(); 
     container.RegisterType<IDecorator, Decorations>(); 

     container.BuildUp(bd); // bd.DerivedDecorations is null 

     Console.WriteLine("Press any key to continue..."); 
     Console.ReadKey(); 
    } 
} 

매우 간단합니다

우리는 공장 패턴을 사용하고 있기 때문에 그 이유에 대해 명확하지 않습니다. 어느 누구도 저에게 어떤 이유를 줄 수 있습니까?

+0

왜 그냥 'Derive temp = new Derive(); container.BuildUp (temp); 파생 bd = 임시; ' –

+0

우리는 공장을 사용하기 때문에 .... 코드는 Base b = GetDerived() .... – allencharp

답변

2

오버플로 일반 BuildUp-Method을 살펴보십시오.

Unity는 지정된 유형의 T를 사용하여 속성을 검사하고 삽입 할 종속성을 결정합니다.

귀하의 경우 명시 적으로 T를 지정하지 않고 "Base"클래스로 확인되는 type inference에 의존합니다 (매개 변수 변수 유형은 "Base"유형 임).

그러니 그에 따라 변수를 선언하거나 non-generic version를 통해 다른 접근 방식을 시도 :

container.BuildUp(typeof(Derived), bd); 

또는 지정된 예를 들어 현재 거의 의미가

container.BuildUp(bd.GetType(), bd); //which resolves to "Derived" 

,하지만 난에 샘플을 기대 단순화를 위해 분해되었다.

+0

과 매우 흡사합니다. 감사합니다! – allencharp

+0

다른 힌트 : 기존 인스턴스를 "buildUp"하지 않고 컨테이너를 통해 인스턴스를 생성하게 할 수도 있습니다.이 경우 전체 유형을 알 수 있습니다. 이것은 "Derived"도 컨테이너에 등록해야한다고 추측합니다. –