私は.Net Web Formsプロジェクト構造を開発しており、アプリケーションのDIフレームワークとしてUnityを使用することに決めました。 Unity [Depedency] Annotationは依存関係自体ではありませんか?
は私のプロジェクトで依存関係を注入するために、私は DIコンテナの外 を作成された最初のオブジェクト を構築に必要があると述べています。それは私たちが質問に来ると言われています。このよう[Dependency]
として
属性注釈が
Attribute
クラスを拡張するクラスです。それらを使用するには、別の名前空間が宣言クラスに含まれていなければなりません。したがって、クラスはMicrosoft.Practices.Unity.DependencyAttribute
クラスに依存します。だから、私たちのクラスは、それが使用するIMyInterfaceの実装を認識していないかもしれませんが、それは依存クラスの具体的な実装を認識している必要がありますか?私がここで紛失しているのは何ですか? DIフレームワークを変更する場合は、プロジェクト全体ですべてのアノテーションを削除する必要があります。コンテナの外部でこのような種類の宣言(設定ファイルまたは何もない)を避ける方法はありますか?
EDIT - >コードここ
/*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"));
}
}
とモジュール
0123の背後にある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コンテナは、この種の制約をあなたにかけません。それが問題を引き起こす場合は、別のコンテナを検討するかもしれません。構造マップ、オートファック、シンプルインジェクタなど – MattDavey
ユニファイドフレームワークの制約ではなく、aspの制約です。ネットWebForms、私はオブジェクトの構築を制御することはできませんので、私はプロパティインジェクションを行う必要があります。それらの他のDIフレームワークは、注入を必要とするクラスを変更することなくプロパティの注入を行うことができますか? –
そうです - [この質問](http://stackoverflow.com/questions/4979453/structuremap-beginner-property-injection)への最初の答えは、そのシナリオを(Structuremapを使用して)正確に説明しています。私は、DIライブラリの大半にこの動作が含まれていると思います。 – MattDavey