.Net Web Forms 프로젝트 구조를 개발 중이며 Unity를 응용 프로그램의 DI 프레임 워크로 사용하기로 결정했습니다. 유니티가 아닙니다 [Depedency] Annotation은 의존성 자체입니까?
내 프로젝트에 종속성을 주입하기 위해 나는 DI 컨테이너의 외부 을 생성 초기 개체 를 구축 할 필요가 있다고 주장한다. 그것이 우리가 질문에 이르렀다 고합니다. 이러한[Dependency]
같은
속성 주석은
Attribute
클래스 확장 클래스이다. 클래스를 사용하려면 다른 네임 스페이스가 선언 클래스에 포함되어야합니다. 따라서 클래스는Microsoft.Practices.Unity.DependencyAttribute
클래스에 종속됩니다. 이제는 클래스가 사용하는 IMyInterface 구현을 인식하지 못할 수도 있지만 종속 클래스의 구체적인 구현을 알고 있어야합니다. 내가 여기서 누락 된 것은 무엇인가? DI 프레임 워크를 변경하려면 프로젝트 전체에서 모든 주석을 제거해야합니다.컨테이너 외부에서 이러한 종류의 선언 (구성 파일 또는 무언가)을 피할 수있는 방법이 있습니까?
편집 -> 코드 여기
/*This is the abstract base class where I want the dependency injection to occur*/
public abstract class BasePage : System.Web.UI.Page
{
private IMyService _dtService;
public IMyService DtService
{
get { return _dtService; }
set { _dtService = value; }
}
}
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
IUnityContainer myContainer = HttpContext.Current.Application.GetDIContainer();
myContainer.RegisterType<IMyService,MyServiceClient>(new
InjectionConstructor("MyServiceWsEndpoint"));
// I have tried this with BasePage too
myContainer.RegisterType<_Default>(new InjectionProperty("DtService"));
}
}
그리고 모듈
뒤에public partial class _Default : BasePage
{
public _Default()
{
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
DataClass dt = DtService.GetDataById(2);
lblWhatever.Text = dt.Description;
}
}
}
글로벌 코드 뒤에 Default.aspx를 코드
public class UnityHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose() { }
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
IHttpHandler currentHandler = HttpContext.Current.Handler;
/*This does not work*/
HttpApplicationStateExtensions.GetDIContainer(HttpContext.Current.Application).BuildUp(
currentHandler.GetType(), currentHandler);
/* While this works*/
HttpApplicationStateExtensions.GetDIContainer(HttpContext.Current.Application).BuildUp<_Default>((_Default)currentHandler);
var currentPage = HttpContext.Current.Handler as Page;
if (currentPage != null)
{
currentPage.InitComplete += OnPageInitComplete;
}
}
}
모듈 내의 코드는 매번 도달합니다. 그 라인은 [Dependency]
속성을 사용할 때 INDEED가 작동합니까?
대부분의 IOC 컨테이너는 당신을 제약의이 종류를 놓지 마십시오. 문제가 발생하면 대체 컨테이너를 고려해보십시오. structmap, autofac, simpleinjector 등이 있습니다. – MattDavey
유니티 프레임 워크의 제한 사항은 아니지만 asp의 제약입니다.닷넷 WebForms, 어디에 개체의 건설을 제어 할 수없는, 그래서 속성 주입을해야합니다. 그 다른 DI 프레임 워크는 주입을 필요로하는 클래스를 변경하지 않고 속성 주입을 할 수 있습니까? –
맞아 - [이 질문] (http://stackoverflow.com/questions/4979453/structuremap-beginner-property-injection)에 대한 첫 번째 대답은 정확히 그 시나리오 (Structuremap 사용)를 설명합니다. 대부분의 DI 라이브러리에는이 동작이 포함되어 있다고 가정합니다. – MattDavey