2011-01-23 2 views
0

ninject 위키와 많은 게시물을 모두 읽었으며 이것을 참조 할 수 있도록 여전히 주입 설정 방법을 이해하지 못했습니다. 재산. 모든 컨트롤러를 만들 때 궁극적으로 일반적인 ViewBag 속성을 설정하려면 기본 클래스 생성자에서 속성을 참조 할 수 있어야합니다. iInitializable 인터페이스를 구현하는 것이 올바른 접근 방식이지만 다시는이를 수행하지 못할 수도 있습니다. 또한 파생 클래스의 코딩을 단순화하기 위해 기본 클래스 생성자에 IMyService를 삽입하지 않기로했습니다. 코드에서 내 최신 시도기본 클래스의 생성자에서 Property Injection으로 정의 된 기본 클래스 속성에 액세스하기

simplifed 버전 :

public class AppController : Controller 
{ 

    [Inject] 
    public IMyService myService{get; set;} 

    public AppController() 
    { 
     //I want to do this, but myService is null 
     //ViewBag.DefaultName = myService.Name; 
    } 

} 

public class DashboardController : AppController 
{ 
    public ActionResult Index() 
    { 
     //myService is accessible, so injection works 
     return View(); 
    } 
} 

답변

1

속성이 생성자 후 주입은 당신이 생성자 주입을 사용하거나 개체가 인스턴스화 된 이후에 액세스 할 필요가 있음을 의미라고합니다. 컨트롤러를 구현할 수 있습니다. IInitializable :

public class AppController : Controller, IInitializable 
{ 
    [Inject] 
    public IMyService MyService { get; set; } 

    public void Initialize() 
    { 
     ViewBag.DefaultName = MyService.Name; 
    } 
} 

public class DashboardController : AppController 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 
+0

Darin, merci. 이것이 내가 필요한 설명이었습니다. – RCM01

관련 문제