我正在开发一个 .Net Web Forms 项目结构,我决定使用 Unity 作为应用程序的 DI 框架。
MSDN-Resolving in Asp.Net声明为了在我的项目中注入(inject)依赖项,我需要建立在 DI container 之外创建的初始对象强>。话虽这么说,我们来到了这个问题。
[Dependency]
等属性注解是扩展Attribute
的类类(class)。为了使用它们,另一个命名空间必须包含在声明类中,从而使我们的类依赖于Microsoft.Practices.Unity.DependencyAttribute
类(class)。那么现在,即使我们的类可能不知道它使用的 IMyInterface 的实现,它也必须知道 Dependency 类的具体实现吗?我在这里想念什么?如果我们要更改 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; }
}
}
Default.aspx背后的代码
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;
}
}
}
全局代码隐藏
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 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]
时,行确实有效吗?属性。
最佳答案
是的,使用 Dependency 属性添加代码将实现与容器紧密耦合。
有几种方法可以确定要注入(inject)的属性:
- 属性
- XML 配置
- 程序化配置
- 自定义容器扩展
避免使用属性的一种方法是注册所有页面,并以编程方式指定要注入(inject)的属性,并根据需要向 BuildUp
提供覆盖:
IUnityContainer container = new UnityContainer();
// Assume we have a logger we are injecting
container.RegisterType<ILogger, Logger>(new ContainerControlledLifetimeManager());
// Register the Dependency Properties for the Page 'MyPage'.
// Property names on MyPage are "Logger"
container.RegisterType<MyPage>(new InjectionProperty("Logger"));
// ...later
IHttpHandler currentHandler = HttpContext.Current.Handler;
// Perform Property Injection.
// Logger will be injected from the existing container registration.
container.BuildUp(currentHandler.GetType(), currentHandler);
关于c# - Unity [Depedency] Annotation 本身不是一个依赖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653005/